Scroll to top in RecyclerView with LinearLayoutManager

前端 未结 4 1740
误落风尘
误落风尘 2020-12-02 20:01

I have a fragment in which there is RecyclerView with LinearLayoutManager in which there are CardView items. There is a floating actio

相关标签:
4条回答
  • 2020-12-02 20:06

    In my case, the requirement was to populate the view in reverse order, which made the layout show the bottom view of the scroll view

    layoutManager.smoothScrollToPosition(mRecyclerView, null, 'last_index') didn't really help.

    My problem was resolved when I made the recycler view to show the child at the last position

    recyclerView.scrollToPosition(length-1)

    0 讨论(0)
  • 2020-12-02 20:14

    Continuing from above comments, ideally, replacing

    mRecyclerView.smoothScrollToPosition(0);
    

    in the onClick of the floating action button with

    mLayoutManager.scrollToPositionWithOffset(0, 0);
    

    should work. You can also remove the SnackBar code, because you don't need it anyways. So, all in all your above method should look like

    public void setFloatingActionButton(final View view) {
        float actionButton = (android.support.design.widget.FloatingActionButton) getActivity()
                .findViewById(R.id.float);
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView
                        .getLayoutManager();
                layoutManager.scrollToPositionWithOffset(0, 0);
            }
        });
    }
    

    And if you say that the above doesnt work, then test if the onClick() is even being called or not. Try adding a log message in it and see if its printed.

    0 讨论(0)
  • 2020-12-02 20:22

    Call 'scrollToPosition(0)' using this:

    public void scrollToPosition(final int position) {
        if (mRecyclerView != null) {
            getHandler().post(new Runnable() {
                @Override
                public void run() {
                    mRecyclerView.scrollToPosition(position);
                    if (position == 0) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                        layoutManager.scrollToPositionWithOffset(0, 0);
                        mScrollView.fullScroll(View.FOCUS_UP);
                    }
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-02 20:25

    Using the method smoothScrollToPosition() worked for me with the newest Android version.

    layoutManager.smoothScrollToPosition(mRecyclerView, null, 0);
    
    0 讨论(0)
提交回复
热议问题