Search code examples
androidandroid-recyclerviewadapter

On insertion of an element to recyclerview, how to scroll to the bottom?


I am practicing to build a chat app. When I insert an item to the recyclerview, I need it to scroll to the bottom. My recyclerview code for now looks like this. I tried adding an onScroll listener and that approach was wrong. Thanks!

        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);
                }
            }
        });```

Solution

  • Add the data observer to your adapter and override onItemRangeInserted.

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