- Custom 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() {
returnscrollType; }}Copy the code
- Custom 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: can be set rolling speed and definition specifies postion in above or below the layoutmanager * / public class AdjustLinearLayoutManager extends LinearLayoutManager { private int scrollType; privatefloat 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); }}Copy the code
- use
mLayoutManager = new AdjustLinearLayoutManager(this);
mLayoutManager.setScrollType(LinearSmoothScroller.SNAP_TO_START);
mRecyclerView.setLayoutManager(mLayoutManager);
Copy the code
Click here for details