Android 如何以编程方式滚动到 ListView 的底部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2537027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to the bottom of ListView programmatically?
提问by UMAR
After calling notifydatasetchanged();
I want to scroll to the bottom of list so that user see the last record in the Listview.
调用后notifydatasetchanged();
我想滚动到列表底部,以便用户看到 Listview 中的最后一条记录。
(I am writing Chat module so for that purpose I need latest record at the bottom of list to be visible)
(我正在编写聊天模块,因此为此我需要列表底部的最新记录可见)
Can any one guide me how to achieve this?
任何人都可以指导我如何实现这一目标吗?
回答by Ribose
I know that this has been answered and you took the answer and it was more than a year ago. But a better way to do this is Transcript Mode. For a demo, see the Android API Demo under Views > Lists > Transcript.
我知道这已经得到了回答,你接受了答案,这是一年多前的事了。但更好的方法是转录模式。有关演示,请参阅 Views > Lists > Transcript 下的 Android API Demo。
You would set the following on your list view in the XML.
您将在 XML 中的列表视图中设置以下内容。
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
It will always work whenever you call notifyDataSetChanged()
. You can set android:transcriptMode
to normal
instead if you want an even better result for chat applications: it will scroll to the bottom only if the last item was already in view. That way your users can view the previous chat without interruption when other users chat.
无论何时您调用它,它都将始终有效notifyDataSetChanged()
。如果您希望聊天应用程序获得更好的结果,您可以改为设置android:transcriptMode
为normal
:仅当最后一个项目已经在视图中时,它才会滚动到底部。这样您的用户就可以在其他用户聊天时不受干扰地查看之前的聊天。
回答by Jim Blackler
Try
尝试
listView.post(new Runnable(){
public void run() {
listView.setSelection(listView.getCount() - 1);
}});
The 'post' seems to be required sometime in my experience, particularly if you have very recently updated the list.
根据我的经验,有时似乎需要“发布”,特别是如果您最近更新了列表。
回答by Toppers
I know its very late to answer but may be it will help someone. Using
android:transcriptMode="alwaysScroll"
will force the listview to scroll to bottom (as here we have used android:stackFromBottom="true"
) even if you'll try to scroll top which usually required most of the time. So instead of android:transcriptMode="alwaysScroll
you can use android:transcriptMode="normal
which will behave similar to the requirement of chat app and will not force the list of scroll always if the user want to see the content at the top.
我知道现在回答已经很晚了,但可能会对某人有所帮助。使用
android:transcriptMode="alwaysScroll"
将强制列表视图滚动到底部(就像我们在这里使用的那样android:stackFromBottom="true"
),即使您尝试滚动顶部,这通常需要大部分时间。因此,android:transcriptMode="alwaysScroll
您可以使用android:transcriptMode="normal
which来代替,其行为类似于聊天应用程序的要求,并且如果用户想要查看顶部的内容,则不会始终强制滚动列表。