我想在不使用setCurrentItem()函数的情况下实现自动视图滚动。因为当我将setCurrentItem()与handler.postdelayed()使用后,它将在设置下一个项目后保持。而且我想要像回收瓶一样光滑的卷轴。可以使用ViewPager实现它吗?
您可以使用ViewPager进行操作。最好的旋转木马是使用Recylerview。但是您需要首先自定义Layoutmanager,以减慢速度,例如轮旋
创建recyclerview
CustomLayoutManager layoutManager = new CustomLayoutManager(getActivity());
layoutManager.setSpeed(1500f);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
然后创建CustomLayoutManager,以更改RecylCerview Scroll的速度
public class CustomLayoutManager extends LinearLayoutManager {
private float MILLISECONDS_PER_INCH = 1100f;
private Context mContext;
public CustomLayoutManager(Context context) {
super(context);
mContext = context;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, final int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(mContext) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return CustomLayoutManager.this.computeScrollVectorForPosition(targetPosition);
}
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH/displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
public void setSpeed(float speed){
this.MILLISECONDS_PER_INCH = speed;
}
}
然后在您的活动或片段中,创建可运行的
Runnable runNews = new Runnable() {
@Override
public void run() {
try {
top_new_rview.smoothScrollToPosition(++counter);
handler.postDelayed(this, replay);
} catch (Exception e) {
handler.removeCallbacks(runNews);
onError(getActivity(), e);
}
}
};