[英]Automatically scrolling RecyclerView list to the bottom upon input
加載活動后,我想滾動到RecyclerView列表的底部。 每次發送或接收消息時,我都需要滾動到底部以閱讀消息。 如何配置它以在發送或接收消息時自動滾動?
這是我到目前為止的代碼:
recyclerView = (RecyclerView) findViewById(R.id.chatWindow_rec);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(Adapter);
我嘗試了StackFromEnd, recyclerview.ScrollToPosition(ListMessage.size())
...沒有結果。 我怎樣才能解決這個問題?
在您的代碼中使用此行,希望對您有所幫助:
layoutManager.setReverseLayout(true);
首先,您應確保適配器中的List <>已用新消息更新。
然后使用RecylcerView.smoothScrollToPosition(List.size())滾動到列表的底部。
或者,使用RecylcerView.smoothScrollToPosition(MessageListAdapter.getItemCount())
您應該選擇第二個選項,因為getItemCount()是適配器的默認方法,只記得覆蓋它即可。
public static RecyclerView.LayoutManager createVerticalLayoutManager(Context context) {
LinearLayoutManager layoutManager = new LinearLayoutManager(context
, LinearLayoutManager.VERTICAL
, false);
return layoutManager;
}
並使您的RecyclerView的寬度和高度為match_parent。
附加新消息時在適配器上調用更新
mMessageAdapter.notifyItemChanged(mMessageAdapter.getItemCount());
上面的代碼行僅使用指定的最新項目更新適配器。
第一個編寫函數以返回適配器中的項目數,然后向適配器添加數據后使用
recyclerView.smoothScrollToPosition(adapter.getCount()-1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.