Detecting scroll position inside a ListView (or ScrollView)

六月ゝ 毕业季﹏ 提交于 2019-12-21 20:56:08

问题


I'm building a chat room application where new events are being polled for every X seconds. Every time that happens, this code updates the RoomAdapter (a custom subclass of ArrayAdapter) with the new data and scrolls it to the bottom:

RoomAdapter adapter = (RoomAdapter) getListAdapter();
for (int i=0; i<newEvents.size(); i++)
 adapter.add(newEvents.get(i));
getListView().setSelection(events.size()-1);

This is fine, except that if the user is scrolling up to glance at the room's history, it's going to jump her down to the bottom when the poll happens. What I'd like to do is have it so that if the user is already at the bottom of the list, it stays there after a poll for new events. If the user's intentionally scrolled upwards, I'd like the user not to be disturbed.

How do I detect when I'm already scrolled to the bottom of a ListView?

Note: I can't do getListView().getSelectedItemPosition(), because as the docs note, calling setSelection when in touch mode does not actually select the item, just scrolls to it.


回答1:


I haven't tried this, but how about getLastVisiblePosition()==getCount()-1? (methods on ListView)




回答2:


But that is not a proper way.
Use
android:transcriptMode
– Behavior of the list when the content changes
– “disabled”, doesn’t scroll
– “normal”, scrolls to the bottom if last item is visible
– “alwaysScroll”, always scrolls to the bottom
android:stackFromBottom
– Stack items in reverse order
– Starts with the last item from the adapter
• Useful for chats
– Messaging, Talk, IRC, etc.



来源:https://stackoverflow.com/questions/1549356/detecting-scroll-position-inside-a-listview-or-scrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!