问题
Is it possible to have a visibility listener on each listview's item? Like: on user sees the item, do something. On item is hidden, do something else.
I want to check when a item "enters" or "exits" the scroll so as to update a second list.
Additionaly my ListView might expand like:
adapter.addAll( (Collection<? extends DBObject>) events);
adapter.notifyDataSetChanged();
I think a way might be to use a global listener to check the items but I am afraid it will get messed up if I add more items to the ListView (above). I have not accomplished anything with that yet
eventList.setOnScrollListener(new OnScrollListener() {
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
回答1:
You can use the onScroll function to calculate that.
eventList.setOnScrollListener(new OnScrollListener() {
int oldFirstVisibleItem = 0;
int oldLastVisibleItem = 0;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > oldFirstVisibleItem) {
for(int i = oldFirstVisibleItem; i < firstVisibleItem; i++) {
onExit(i);
}
}
if (firstVisibleItem < oldFirstVisibleItem) {
for(int i = firstVisibleItem; i < oldFirstVisibleItem; i++) {
onEnter(i);
}
}
int lastVisibleItem = firstVisibleItem + visibleItemCount - 1;
if (lastVisibleItem < oldLastVisibleItem) {
for(int i = oldLastVisibleItem+1; i <= lastVisibleItem; i++) {
onExit(i);
}
}
if (lastVisibleItem > oldLastVisibleItem) {
for(int i = oldLastVisibleItem+1; i <= lastVisibleItem; i++) {
onEnter(i);
}
}
oldFirstVisibleItem = firstVisibleItem;
oldLastVisibleItem = lastVisibleItem;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
public void onEnter(int position) {
// Handle an item coming into view.
}
public void onExit(int position) {
// Handle an item going out of view.
}
回答2:
The answer is in your question.
One of the methods that you override in the onScrollListener() is
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
The parameters passed include the firstVisibleItem
, and the visibleItemCount
. you can use these two numbers to figure out which items are currently visible.
Just keep in mind that onScroll is called very often while scrolling.
来源:https://stackoverflow.com/questions/21414125/listview-adapter-item-visibility-listener