我想在不使用 setCurrentItem() 函数的情况下实现自动 viewpager 滚动。因为当我将 setcurrentitem() 与 handler.postdelayed() 一起使用时,它会在设置下一个项目后保持不变。我想要一个像 recyclerview 一样的平滑滚动。用viewpager可以实现吗?
问问题
300 次
1 回答
1
你可以用 ViewPager 来做。最好的轮播是使用recylerview。但是你需要先自定义 LayoutManager 来像轮播一样减慢速度
创建回收站视图
CustomLayoutManager layoutManager = new CustomLayoutManager(getActivity());
layoutManager.setSpeed(1500f);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
然后创建CustomLayoutManager来改变recyclerview滚动的速度
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);
}
}
};
于 2016-12-01T01:27:19.343 回答