How to get the selected item from ListView?

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

提交回复
热议问题