如何滚动到RecyclerView的底部? scrollToPosition不起作用 [英] How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work
问题描述
我想在加载活动后滚动到RecyclerView列表的底部。
I'd like to scroll to the bottom of the RecyclerView list after loading the activity.
GENERIC_MESSAGE_LIST = (ArrayList) intent.getExtras().getParcelableArrayList(ConversationsAdapter.EXTRA_MESSAGE);
conversationView = (RecyclerView) findViewById(R.id.list_messages);
conversationView.setHasFixedSize(true);
conversationViewLayoutManager = new LinearLayoutManager(this);
conversationView.setLayoutManager(conversationViewLayoutManager);
conversationViewAdapter = new ConversationAdapter(GENERIC_MESSAGE_LIST, this);
conversationView.setAdapter(conversationViewAdapter);
conversationView.scrollTo(...)
抛出一个关于在RecyclerView中不受支持的例外,而 conversationView.scrollToPosition(...)
似乎什么也没做。
conversationView.scrollTo(...)
throws an exception about being not supported in RecyclerView, and conversationView.scrollToPosition(...)
doesn't seem to do anything.
在上面的代码块之后,我添加了
After the above block of code, I added
conversationView.scrollToPosition(GENERIC_MESSAGE_LIST.size() + 1)
不起作用。 GENERIC_MESSAGE_LIST
中有30个元素。
which doesn't work. There are 30 elements in GENERIC_MESSAGE_LIST
.
推荐答案
只需设置 setStackFromEnd = true
或 setReverseLayout = true
以便LLM将布局项目来自结束。
Just set setStackFromEnd=true
or setReverseLayout=true
so that LLM will layout items from end.
这两者之间的区别在于 setStackFromEnd
将设置视图以显示最后一个元素,布局方向将保持不变。 (因此,在从左到右的水平Recycler视图中,将显示最后一个元素,向左滚动将显示较早的元素)
The difference between these two is that setStackFromEnd
will set the view to show the last element, the layout direction will remain the same. (So, in an left-to-right horizontal Recycler View, the last element will be shown and scrolling to the left will show the earlier elements)
然后 setReverseLayout
将更改适配器添加的元素的顺序。布局将从最后一个元素开始,该元素将在LTR Recycler View中最左侧,然后向右滚动将显示较早的元素。
Whereas setReverseLayout
will change the order of the elements added by the Adapter. The layout will start from the last element, which will be the left-most in an LTR Recycler View and then, scrolling to the right will show the earlier elements.
示例:
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
_listView.setLayoutManager(linearLayoutManager);
参见文档了解详情。
这篇关于如何滚动到RecyclerView的底部? scrollToPosition不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!