【问题标题】:On insertion of an element to recyclerview, how to scroll to the bottom?在将元素插入到 recyclerview 时,如何滚动到底部?
【发布时间】:2020-08-27 12:00:41
【问题描述】:

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

【问题讨论】:

    标签: android android-recyclerview adapter


    【解决方案1】:

    将数据观察器添加到您的适配器并覆盖 onItemRangeInserted。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多