简体   繁体   English

检测ListView(或ScrollView)中的滚动位置

[英]Detecting scroll position inside a ListView (or ScrollView)

I'm building a chat room application where new events are being polled for every X seconds. 我正在构建一个聊天室应用程序,每隔X秒轮询一次新事件。 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(ArrayAdapter的自定义子类)并将其滚动到底部:

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? 如何检测我何时已滚动到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. 注意:我不能做getListView()。getSelectedItemPosition(),因为正如文档所说,在触摸模式下调用setSelection实际上并没有选择项目,只是滚动到它。

I haven't tried this, but how about getLastVisiblePosition()==getCount()-1 ? 我没试过这个,但getLastVisiblePosition()==getCount()-1怎么样? (methods on ListView ) ListView方法)

But that is not a proper way. 但这不是一个正确的方法。
Use 采用
android:transcriptMode 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 - “alwaysScroll”,始终滚动到底部
android:stackFromBottom android:stackFromBottom
– Stack items in reverse order - 以相反的顺序堆叠项目
– Starts with the last item from the adapter - 从适配器的最后一项开始
• Useful for chats •用于聊天
– Messaging, Talk, IRC, etc. - 消息,谈话,IRC等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM