ListView setOnItemClickListener not executing
I am new to android and although I got this working before on a simpler project, I can not for the life of me figure out what is going on.
Here is the code for my ListActivity class:
public class ResultsActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get rid of the default title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Bundle extras = this.getIntent().getExtras();
if (extras != null)
{
String[] results = extras.getStringArray("results_to_display");
this.setListAdapter(new ArrayAdapter<String>(this, 开发者_运维百科R.layout.result_list_item, results));
ListView listView = this.getListView();
listView.setTextFilterEnabled(true);
Toast.makeText(getApplicationContext(), "hello there", Toast.LENGTH_LONG).show();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d(ACTIVITY_SERVICE, "here now");
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
this.setContentView(R.layout.result_list);
}
}
I am able to get the list to display the content that I want, however, when clicking on an item it looks like onItemClick does not get executed. I have put a breakpoint in there as well.
Here is my layout file (not sure if it makes a difference)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contentContainer"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Any help would be appreciated!
In a ListActivity you can override onListItemClick:
public class ResultsActivity extends ListActivity {
protected void onListItemClick (ListView l, View v, int position, long id){
}
}
EDIT
I found the problem. You set the layout (with setContentView) at the end of onCreate. The ListView you are setting the OnItemClickListener on is not the ListView you are seeing.
The ListActivity creates its own contentView if you do not set one yourself. So you added the OnClickListener on the "default" ListView and at the end of onCreate the default one was replaced with a new one because setContentView was called.
Actually one can create a ListActivity without setting the contentView.
To solve the problem move setContentView at the top of onCreate.
精彩评论