The "conversion" from dataset position and "child view position" in ListView
is wrong.
The children views in ListView
are numbered from 0 to listView.getChildCount() - 1
. A position in the dataset, as the variable position
should be, goes from 0 to adapter.getCount() - 1
. The method listview.getFirstVisiblePosition()
returns the first dataset position that is visible on the screen, i.e. what dataset position corresponds to the 0th view in ListView
.
Now say you have 15 items in your Adapter
, you have 10 items in your ListView
on screen, and you scrolled down by 2 items. This means the visible item positions in the dataset are from 2 to 11, but the "child view positions" are always from 0 to 9. listview.getFirstVisiblePosition()
would return 2.
By mean of this example, it's easy to convert from "dataset position" to "child view position": the child view position is basically the dataset position minus the first visible dataset position:
int firstVisibleElement = postListView.getFirstVisiblePosition();
int lastVisibleElement = postListView.getLastVisiblePosition();
if (position >= firstVisibleElement && position <= lastVisibleElement) {
View view = postListView.getChildAt(position - firstVisibleElement);
}