tags:

views:

2956

answers:

3

Hi,

How do I listen to click event on a ListView?

This is what I have now

ListView list = (ListView)findViewById(R.id.ListView01);  
...  
list.setAdapter(adapter);  

When I do the following

list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {  
   public void onItemSelected(AdapterView parentView, View childView, int position, long id) {  
            setDetail(position);  
        }
        public void onNothingSelected(AdapterView parentView) {  

        }  
      });  

That doesn't seem to do anything on click.
And all those code live within a class that extends Activity.

Thanks, Tee

+3  A: 

On your list view, use setOnItemClickListener

David Hedlund
Thanks David. Geezzz, I tried setOnClickListener and setOnItemSelectedListener but missed reading setOnItemClickListener.Thanks,Tee
teepusink
+4  A: 

You need to set the inflated view "Clickable" and "able to listen to click events" in your adapter class getView() method.

convertView = mInflater.inflate(R.layout.list_item_text, null);
convertView.setClickable(true);
convertView.setOnClickListener(clickListener);

and declare the click listener in your ListActivity as follows,

public OnClickListener myClickListener = new OnClickListener() {
public void onClick(View v) {
                 //code to be written to handle the click event
    }
};

This holds true only when you are customizing the Adapter by extending BaseAdapter.

Refer the http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html for more details

Vijay C
+3  A: 

The two answers before mine are correct - you can use OnItemClickListener.

It's good to note that the difference between OnItemClickListener and OnItemSelectedListener, while sounding subtle, is in fact significant, as item selection and focus are related with the touch mode of your AdapterView.

By default, in touch mode, there is no selection and focus. You can take a look here for further info on the subject.

Dimitar Dimitrov