在将元素插入到 recyclerview 时,如何滚动到底部?
On insertion of an element to recyclerview, how to scroll to the bottom?
我正在练习构建一个聊天应用程序。当我将一个项目插入 recyclerview 时,我需要它滚动到底部。我的 recyclerview 代码现在看起来像这样。我尝试添加一个 onScroll 侦听器,但这种方法是错误的。谢谢!
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
((SimpleItemAnimator) binding.chatRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
linearLayoutManager.setReverseLayout(true);
binding.chatRecyclerView.setLayoutManager(linearLayoutManager);
binding.chatRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
Log.i(TAG, "onScrolled: " + firstVisiblePosition);
if (dy < 0) {
binding.chatDate.setVisibility(View.VISIBLE);
binding.chatDate.setText(sfdMainDate.format(new Date(chatadapter.getItem(firstVisiblePosition).getTimestamp())));
} else if (dy > 0) {
binding.chatDate.setVisibility(View.GONE);
}
}
});```
将数据观察器添加到您的适配器并覆盖 onItemRangeInserted。
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
binding.chatRecyclerView.smoothScrollToPosition(0);
}
});```
我正在练习构建一个聊天应用程序。当我将一个项目插入 recyclerview 时,我需要它滚动到底部。我的 recyclerview 代码现在看起来像这样。我尝试添加一个 onScroll 侦听器,但这种方法是错误的。谢谢!
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
((SimpleItemAnimator) binding.chatRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
linearLayoutManager.setReverseLayout(true);
binding.chatRecyclerView.setLayoutManager(linearLayoutManager);
binding.chatRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
Log.i(TAG, "onScrolled: " + firstVisiblePosition);
if (dy < 0) {
binding.chatDate.setVisibility(View.VISIBLE);
binding.chatDate.setText(sfdMainDate.format(new Date(chatadapter.getItem(firstVisiblePosition).getTimestamp())));
} else if (dy > 0) {
binding.chatDate.setVisibility(View.GONE);
}
}
});```
将数据观察器添加到您的适配器并覆盖 onItemRangeInserted。
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
binding.chatRecyclerView.smoothScrollToPosition(0);
}
});```