Search code examples
androidandroid-listviewonlongclicklistener

ListView: onItemLongClick Toasts Object


I want to toast Text of selected list item in ListView. I'm using Custom Adapter. I tried this code.

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,final int pos,
        final long id) {
    String text=String.valueOf(lv.getItemAtPosition(pos));
    Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
  }

But it's Toasting Object name like com.demo.CustomList@413ffb10. Can anyone tell me how to Toast respective item?

Note: The above code works for Simple Adapter,but not for Custom Adapter


Solution

  • Assuming that the list view has objects of the type CustomList as per your code it is displaying the default toString() method of your CutsomList class. You should instead access the variables that you would like to display and toast it.

    For example:

           public class CustomList {
                      String title;
    
            public String getTitle(){
            return name;
            }
    }
    

    And in the onClick you can do the following:

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,final int pos,
            final long id) {
         CustomList customList= (CustomList )lv.getItemAtPosition(pos);
    
        Toast.makeText(getActivity(), customList.getTitle(), Toast.LENGTH_SHORT).show();
      }
    

    This is exactly what you are looking for. Hope that helps.