android 在recyclerview中插入一个元素时,如何滚动到底部?

ubof19bj  于 2023-02-10  发布在  Android
关注(0)|答案(1)|浏览(213)

我正在练习构建一个聊天应用程序。当我插入一个项目到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);
                }
            }
        });```
mcvgt66p

mcvgt66p1#

将数据观察器添加到适配器并重写onItemRangeInserted。

adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                binding.chatRecyclerView.smoothScrollToPosition(0);
            }
        });

相关问题