1. 程式人生 > >android recyclerView滑動到固定位置

android recyclerView滑動到固定位置

因為recyclerView的scrillToPosition(int position)只能移動到介面顯示的位置,所以當滑到介面顯示的位置時,還要手動再劃一點位置
1.要滑動的位置在螢幕的上方直接滑動到該位置,即顯示在螢幕頂部
2.要滑動的位置在螢幕的中間,向上滑動一段距離
3.要滑動的位置在螢幕的下方,首先滑動到可見位置,再呼叫2的滑動方式
 

package com.dejun.commonsdk.util;

import android.support.v7.widget.RecyclerView;

/**
 * Author:DoctorWei
 * Time:2018/12/17 20:22
 * Description:
 * email:
[email protected]
*/ public class RVMoveToPosition { //目標項是否在最後一個可見項之後 private boolean mShouldScroll; //記錄目標項位置 private int position; private RecyclerView mRecyclerView; public RVMoveToPosition( RecyclerView mRecyclerView, final int position) { this.mRecyclerView=mRecyclerView; this.position = position; } public static RVMoveToPosition createRVMoveToPosition(RecyclerView mRecyclerView, final int position){ return new RVMoveToPosition(mRecyclerView,position); } /** * 滑動到指定位置 */ public void smoothMoveToPosition() { // 第一個可見位置 int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0)); // 最後一個可見位置 int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1)); if (position < firstItem) { // 第一種可能:跳轉位置在第一個可見位置之前 mRecyclerView.smoothScrollToPosition(position); } else if (position <= lastItem) { // 第二種可能:跳轉位置在第一個可見位置之後 int movePosition = position - firstItem; if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) { int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); } } else { // 第三種可能:跳轉位置在最後可見項之後 mRecyclerView.smoothScrollToPosition(position); mShouldScroll = true; } } public void setListener( final onScrollStateChanged onScrollStateChanged){ mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (onScrollStateChanged!=null){ onScrollStateChanged.onScrollStateChanged(recyclerView, newState); } if (mShouldScroll&& RecyclerView.SCROLL_STATE_IDLE == newState) { mShouldScroll = false; smoothMoveToPosition(); } } }); } private onScrollStateChanged onScrollStateChanged; public interface onScrollStateChanged{ void onScrollStateChanged(RecyclerView recyclerView, int newState); } }