Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first visible View from an Android ListView

Is there a way to get the first visible View out of the ListView in Android?

I can get the data that backs the first View in the Adapter but it seems I can't get the first View in ListView.

I want to change the first visible view after a scroll action finished. I know that I should not save references to the view.

like image 547
Janusz Avatar asked Jun 24 '10 14:06

Janusz


4 Answers

Indeed listView.getChildAt(listView.getFirstVisiblePosition()) gives the first visible item,
BUT it could be half visible list item.

To get first completely visible list item,

if (listView.getChildAt(0).getTop() < 0) {
     int firstCompletelyVisiblePos = listView.getFirstVisiblePosition() + 1;
}
like image 63
Vijay C Avatar answered Nov 11 '22 20:11

Vijay C


Actually ListView items are just children of ListView. So first visible ListView item is:

listView.getChildAt(0)
like image 44
Fedor Avatar answered Nov 11 '22 22:11

Fedor


ListView has a function getFirstVisiblePosition so to get the first visible view, the code would be:

listView.getChildAt(listView.getFirstVisiblePosition());

like image 29
Austin Wagner Avatar answered Nov 11 '22 21:11

Austin Wagner


Object item = listView.getItemAtPosition(listView.getFirstVisiblePosition());

For first completely visible list item:

int pos = listView.getFirstVisiblePosition();
if (listView.getChildCount() > 1 && listView.getChildAt(0).getTop() < 0) pos++;
Object item = listView.getItemAtPosition(pos);
like image 24
Enyby Avatar answered Nov 11 '22 22:11

Enyby