我想在不使用setCurrentItem()函数的情况下实现自动viewpager滚动。因为当我使用setcurrentitem()和handler.postdelayed()时,它在设置下一个项目后保持不变。我想要一个像recyclerview一样的平滑滚动。是否可以通过viewpager实现它?
答案 0 :(得分:1)
您可以使用ViewPager执行此操作。最好的轮播就像使用recylerview。但你需要首先自定义LayoutManager以降低速度,如轮播
创建Recyclerview
CustomLayoutManager layoutManager = new CustomLayoutManager(getActivity());
layoutManager.setSpeed(1500f);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
然后创建CustomLayoutManager以更改recylcerview滚动的速度
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
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);
}
}
};