JB_User
JB_User

Reputation: 3267

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?

Upvotes: 0

Views: 596

Answers (3)

Sam
Sam

Reputation: 86948

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.

Upvotes: 1

Pavan tej
Pavan tej

Reputation: 183

You can get the position by using onitem click listener.by using on item click listener you can get position of selected item in the list.And you can put this position in Toast

Upvotes: 0

Yugesh
Yugesh

Reputation: 4092

Try this

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

  }                 
});

Upvotes: 1

Related Questions