Skip to content Skip to sidebar Skip to footer

Onitemclicklistener And Onclicklistener In Listview

I have a custom view for each row in a custom ListAdapter and I am trying to perform onClick action and get the row position in the list where the click came from.

Solution 1:

You could assign the proper OnClickListener to each ImageView and TextView from inside your ListAdapter's overridden getView method.

Inside that method you know the item's position, so you can pass it to the custom listener classes, and use it there as you want:

@Overridepublic View getView(finalint position, View convertView, ViewGroup parent)
{
    // TODO: instantiate the layout // here I call a super methodfinalViewview=super.getView(position, convertView, parent);
    finalTextViewtextView= (TextView)view.findViewById(R.id.itemTxt);
    textView.setOnClickListener(newOnClickListener()
    {
        @OverridepublicvoidonClick(View v)
        {
            Log.i("Click", "TextView clicked on row " + position);
        }
    });
    finalImageViewimageView= (ImageView)view.findViewById(R.id.delBtn);
    imageView.setOnClickListener(newOnClickListener()
    {
        @OverridepublicvoidonClick(View v)
        {
            Log.i("Click", "ImageView clicked on row " + position);
        }
    });
    return view;
}

Solution 2:

The other possible option to have the OnClickListener in the same class as the creating activity is to add to the activity implements OnItemClickListener.

publicclassDisplayListCustomextendsActivityimplementsOnItemClickListener

Then set the custom list to listen

ListViewlist= (ListView)findViewById(R.id.custom_list);
list.setClickable(true);
list.setOnItemClickListener(this);
list.setAdapter(newCustomListAdapter(getApplicationContext(), listItems));

Finally in the onItemClick return, you can find the inner views by using resource ID

publicvoidonItemClick(AdapterView<?> parent, View v, int position, long id) {
    LinearLayoutlistItem= (LinearLayout) v;
    TextViewclickedItemView= (TextView) listItem.findViewById(R.id.name);
    StringclickedItemString= clickedItemView.getText().toString();
    Log.i("DisplayListCustom", "Click detected " + clickedItemString + ", position " + Integer.toString(position));

This is the solution I went with. I used LinearLayout for my custom layout container, but I assume the same applies to RelativeLayout.

Solution 3:

You need to extend your TextView etc, override the click method, do the appropriate actions and then the trick is to return false so it's then propagated to the listview.

Post a Comment for "Onitemclicklistener And Onclicklistener In Listview"