John
John

Reputation: 1051

How to get the actual index of a child in a ListView?

I am currently using the getChildAt method for getting the child rows inside a ListView. The problem with this is that it only gets the child correctly if the ListView is scrolled all the way to the top.

If I were to scroll down a bit so that the first row is hidden and call the getChildAt method for position 1 it would get the view that is third in the ListView.

Is there a way to get the child view with an actual position rather than the position visible on the screen? So that in the case above the getChildAt would still return a view (2nd child) even if it isn't visible on the screen.

Upvotes: 2

Views: 539

Answers (1)

sadat
sadat

Reputation: 4342

public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

if (pos < firstListItemPosition || pos > lastListItemPosition ) {
    return listView.getAdapter().getView(pos, null, listView);
} else {
    final int childIndex = pos - firstListItemPosition;
    return listView.getChildAt(childIndex);
}}

reference: android - listview get item view by position

Upvotes: 2

Related Questions