android onItemClick silently fails
I'm displaying some sql data in a list via a ListAdapter. Everything works fine except when I try to set a click listener to each item in the list. Nothing happens when I click any of the items; no error messages, it just silently fails.
public class Notes extends ListActivity implements OnClickListener {
开发者_JAVA百科 private static final String TAG = "Notes";
private NotesData notes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notes = new NotesData(this);
try {
Cursor cursor = getNotes();
showNotes(cursor); /* set the cursor to the listadapter */
ListView ls = (ListView) findViewById(android.R.id.list);
ls.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v,
int position,long id) {
Toast.makeText(getApplicationContext(),"clicked",
Toast.LENGTH_SHORT).show();
}
});
} finally {
notes.close();
}
}
main.xml, containing the listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/new_note_button"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/new_note"/>
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/empty"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/empty"/>
</LinearLayout>
Is there something I'm missing?
Nothing is missing, your code is completely correct, just replace the getApplicationContext() to "this" could probably solve the problem, as what you need to pass is a reference to the context of the current component rather than the context of the current process.
Hope it helps. Hass.
You need to add android:focusable="false"
to the button you have in your main.xml file. The button is taking the focus away from the list item.
This is solve your problem for sure.
I guess your list item is set clickable. (view.setClickable(true))
onItemClick will to be called when the list item is clickable.
I'd recommend throwing something like this in your try statement
try{
//yourstuff
} catch (Exception e) {
e.printStackTrace();
}
And then check to see what error message is thrown. It's possible that it's throwing the error when it sets the onClickListener, maybe there's something invalid, but as long as all of that is in a try statement, it's not going to give you any helpful error message. So you could also just pull as much out of the try statement as possible until you find the problem. :-)
精彩评论