简体   繁体   中英

How to Get The Selected Item in ListView?

I'm building a simple App with a ListView in it. In the Java code, I'm trying to figure out which item(s) is currently selected. From the ListView documentation at http://developer.android.com/reference/android/widget/ListView.html I see there's a method in the ListView class called

public void setSelection (int position) 

I looked for a similarly named method named getSelection(), but there is none.

So, first, how do I determine which item in my ListView is currently selected? I already have the object for the ListView, so I just need the method to tells me which item the user clicked on.

ListView myLV = (ListView) findViewByID(R.id.myListView);

Also, can I define a "callback" function which is called whenever an item is selected?

Finally, how can I use the documentation to figure this out? This is a very basic question which I should be able to figure out on my own. I did what seems to be the right thing: I looked at the Official Developer pages for the ListView class, but it didn't provide the answer. How can I answer these (basic) questions for myself?

I looked for a similarly named method named getSelection(), but there is none. So, first, how do I determine which item in my ListView is currently selected?

The super class AdapterView has getSelectedItem() , along with getSelectedItemId() and others. AbsListView has getSelectedView() too. But these only tend to work when you have used setChoiceMode()

The OnItemClickListener lets you know which it is clicked as it is clicked.

Finally, how can I use the documentation to figure this out?

You were right to start in ListView's documentation, but go to the "Inherited Methods" section and check the super classes as well.

Try this

  mylv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> myAdapter, View v, int position, long lng) {
    String selectedFromList =(String) (mylv.getItemAtPosition(position));

  }                 
});

您可以通过使用onitem click listener获得该位置。通过使用项目点击监听器,您可以获得列表中所选项目的位置。您可以将此位置放在Toast中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM