RecyclerView滚动位置,滚动速度设置

929 阅读1分钟
  1. 自定义Scroller
import android.content.Context;
import android.util.DisplayMetrics;

import androidx.annotation.IntDef;
import androidx.recyclerview.widget.LinearSmoothScroller;

public class AdjustLinearSmoothScroller extends LinearSmoothScroller {

    private int scrollType;
    private static float time;
    public static final float DEFAULT_MILLISECONDS_PER_INCH = 25f;


    @IntDef({SNAP_TO_ANY, SNAP_TO_START, SNAP_TO_END})
    public @interface ScrollType {
    }


    public AdjustLinearSmoothScroller(Context context, @ScrollType int scrollType) {
        super(context);
        this.scrollType = scrollType;
    }

    @Override
    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
        return time / displayMetrics.densityDpi;
    }

    public static void setTime(float milliseconds) {
        time = milliseconds;
    }

    @Override
    protected int getVerticalSnapPreference() {
        return scrollType;
    }
}

  1. 自定义LayoutManager
import android.content.Context;
import android.util.AttributeSet;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.koolearn.toefl2019.ui.recyclerview.AdjustLinearSmoothScroller.DEFAULT_MILLISECONDS_PER_INCH;

/**
 * Description:可以自己设置滚动速度和定义指定postion在上边还是在下边的layoutmanager
 */

public class AdjustLinearLayoutManager extends LinearLayoutManager {

    private int scrollType;
    private float time = DEFAULT_MILLISECONDS_PER_INCH;

    public AdjustLinearLayoutManager(Context context) {
        super(context);
    }

    public AdjustLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public AdjustLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }


    public void setMillisecondsPerInch(float time) {
        this.time = time;
    }

    public void setScrollType(@AdjustLinearSmoothScroller.ScrollType int scrollType) {
        this.scrollType = scrollType;
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        AdjustLinearSmoothScroller.setTime(time);
        AdjustLinearSmoothScroller scroller = new AdjustLinearSmoothScroller(recyclerView.getContext(), scrollType);
        scroller.setTargetPosition(position);
        startSmoothScroll(scroller);
    }

}

  1. 使用
mLayoutManager = new AdjustLinearLayoutManager(this);
mLayoutManager.setScrollType(LinearSmoothScroller.SNAP_TO_START);
mRecyclerView.setLayoutManager(mLayoutManager);

详情戳这里