Janusz
Janusz

Reputation: 189454

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.

Upvotes: 10

Views: 22695

Answers (6)

Enyby
Enyby

Reputation: 4420

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);

Upvotes: 1

surya
surya

Reputation: 607

You can use the following code:

for (int i = 0; i <= conversationListView.getLastVisiblePosition() - conversationListView.getFirstVisiblePosition(); i++) {
        View listItem = conversationListView.getChildAt(i);
}

Upvotes: 0

Sanal
Sanal

Reputation: 1

listView.scrollBy(0, -40);

This works very well

Upvotes: -2

Vijay C
Vijay C

Reputation: 4869

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;
}

Upvotes: 4

Austin Wagner
Austin Wagner

Reputation: 1081

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

listView.getChildAt(listView.getFirstVisiblePosition());

Upvotes: 4

Fedor
Fedor

Reputation: 43412

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

listView.getChildAt(0)

Upvotes: 13

Related Questions