How to get the selected item from ListView?

前端 未结 9 616
我寻月下人不归
我寻月下人不归 2020-11-29 03:26

in my Android app I have created a ListView component called myList, and filled it with objects of my own custom type:

class MyClass{

    private String di         


        
相关标签:
9条回答
  • 2020-11-29 03:54

    By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:

    myList.getSelectedItem();
    

    The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:

    myList.getItemAtPosition(position);
    
    0 讨论(0)
  • 2020-11-29 03:56

    You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

    What you should change, in your above example, is to

    public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
        MyClass item = (MyClass) adapter.getItem(position);
    }
    
    0 讨论(0)
  • 2020-11-29 04:01

    On onItemClick :

    String text = parent.getItemAtPosition(position).toString();
    
    0 讨论(0)
  • 2020-11-29 04:02
    myList.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
          MyClass selItem = (MyClass) adapter.getItem(position);
       }
    }
    
    0 讨论(0)
  • 2020-11-29 04:07

    MyClass selItem = (MyClass) myList.getSelectedItem(); //

    You never instantiated your class.

    0 讨论(0)
  • 2020-11-29 04:08

    Since the onItemClickLitener() will itself provide you the index of the selected item, you can simply do a getItemAtPosition(i).toString(). The code snippet is given below :-

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    
                String s = listView.getItemAtPosition(i).toString();
    
                Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_LONG).show();
                adapter.dismiss(); // If you want to close the adapter
            }
        });
    

    On the method above, the i parameter actually gives you the position of the selected item.

    0 讨论(0)
提交回复
热议问题