纠正:Android RecyclerView滚动到指定位置并置顶(滚动方法、移动置顶、定位滑动到指定位置item)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weimingjue/article/details/82805361

最近博主发现让RecyclerView滑动到某一位置并置顶的博客一大堆,抄的是完全一模一样。此外,虽然这些博客“解决”了这些问题,但这种解决方案过于浅显、粗暴,甚至都违背了开发思想。遂在此纠正这种错误。

RecyclerView提供了几种移动的方法

scrollToPosition

scrollTo

scrollBy

smoothScrollBy

smoothScrollToPosition

虽然里面有移动到指定位置的方法scrollToPosition(直接闪现至某一位位置)、smoothScrollToPosition(惯性滑动至某一位置)但是貌似都不尽人意,因为他们只保证能够展示出来,并不能保证在第一位。而此时如果你打开源码就会发现,原来全都是调用的LayoutManager移动方法,首先打开我们耳熟能详的LinearLayoutManager惊喜就在眼前

scrollToPosition

在scrollToPosition旁边有木有一个很像的方法

    @Override
    public void scrollToPosition(int position) {
        mPendingScrollPosition = position;
        mPendingScrollPositionOffset = INVALID_OFFSET;
        if (mPendingSavedState != null) {
            mPendingSavedState.invalidateAnchor();
        }
        requestLayout();
    }
    public void scrollToPositionWithOffset(int position, int offset) {
        mPendingScrollPosition = position;
        mPendingScrollPositionOffset = offset;
        if (mPendingSavedState != null) {
            mPendingSavedState.invalidateAnchor();
        }
        requestLayout();
    }

当看到offset时也许就会明白:没错,这个就是item移动后相对父控件的偏移值,传入0就会有你想要的

smoothScrollToPosition


    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
            int position) {
        LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext());
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }

而smoothScrollToPosition原来仅仅是new了一个LinearSmoothScroller然后调用startSmoothScroll

我们只需要自定义一个LinearSmoothScroller(直接复制他们的吧,博主也很懒的)

    public class TopSmoothScroller extends LinearSmoothScroller {
        TopSmoothScroller(Context context) {
            super(context);
        }
        @Override
        public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
            return boxStart - viewStart;//得到的就是置顶的偏移量
        }
    }

 然后调用LinearLayoutManager的startSmoothScroll即可

                    final TopSmoothScroller mScroller = new TopSmoothScroller(getActivity());
                    mScroller.setTargetPosition(integer);
                    mManager.startSmoothScroll(mScroller);

是否恍然大悟:其实我们并不需要什么bd,也不需要修改LinearLayoutManager,仅仅需要几行代码即可解决。

多看看源码,多思考思考,你也可以。

真理往往掌握在少数人手中,你是不是其中一员呢?

转载请注明出处:王能的博客https://blog.csdn.net/weimingjue/article/details/82805361

猜你喜欢

转载自blog.csdn.net/weimingjue/article/details/82805361