34

I have an Android ListView created with a SimpleAdapter that has more items in it than fit in the screen. After the list has been scrolled, I need to get the position in the data model of the first visible item in the list.

Basically I want a function like: listView.getChildAt(0).getPositionInDataModel().

Adapter has a few functions in it, like getItemId(position) that looked useful; however, the SimpleAdapter implementation just returns the passed in position, not a row id like I'd hoped.

A brute force solution would be to get the View at index 0, and compare it to the view for each item in the adapter. However, there doesn't seem to be an easy way to get the view for a particular position from the adapter.

Anyone have any thoughts?

Macarse
  • 91,829
  • 44
  • 175
  • 230
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82

3 Answers3

91

It's very easy. Just use ListView.getFirstVisiblePosition() + indexYouWant. For instance, to get the position in the adapter of the 2nd child displayed in the ListView, just use getFirstVisiblePosition() + 1.

No need for all the scary stuff shown in the reply above :)

Macarse
  • 91,829
  • 44
  • 175
  • 230
Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • 2
    Wow, I can't believe I missed that. I was looking all over for a function like that. Must have been because it's defined in a parent class where I didn't expect it. Still getting used to this javadoc style... Thanks for pointing it out! – Cheryl Simon Jan 04 '10 at 21:49
  • Some of the views between getFirstVisiblePosition() and getLastVisiblePosition() return null in my Gridview. I'm recycling the views though - is that the cause? I'd expect that visible views would be guaranteed not to be null especially since I can visually see they are not. – Laurent Feb 27 '15 at 08:49
1
listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) 
    {
        AisleId= parent.getSelectedItemId();
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
});

In this we will get list item Id parent.getSelectedItemId();

Matthias
  • 7,432
  • 6
  • 55
  • 88
varma
  • 11
  • 2
-1

Simply use the getPositionForView(View) (see documentation). The main advantage of this method is it also works with descendant Views of an item.

Cyril Mottier
  • 1,614
  • 1
  • 12
  • 10