How to get the selected item from ListView?

前端 未结 9 617
我寻月下人不归
我寻月下人不归 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 04:12

    Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :

    myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
         MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
             }
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {
                    // your stuff
                }
            });
    
    0 讨论(0)
  • 2020-11-29 04:14

    In touch mode, there is no focus and no selection. Your UI should use a different type of widget, such as radio buttons, for selection.

    The documentation on ListView about this is terrible, just one obscure mention on setSelection.

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

    Though I am using kotlin, the following code answered your question. This return selected item:

    val item = myListView.adapter.getItem(i).toString()
    

    The following is the whole selecteditem Listener

    myListView.setOnItemClickListener(object : OnItemClickListener {
           override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
                            id: Long) {
               val item = myListView.adapter.getItem(i).toString()
    
           }
        })
    

    The code returns the item clicked by its index i as shown in the code

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