I want to implement automatic viewpager scroll without using setCurrentItem() function. Because when i use setcurrentitem() with handler.postdelayed() it holds on after setting next item. and i want a smooth scroll like in recyclerview. Will it be possible to achieve it with viewpager?
Asked
Active
Viewed 309 times
1 Answers
1
you can do it with ViewPager. best carousel like is using the recylerview. but you need to custom the LayoutManager first to slow down the speed like carousel
Create Recyclerview
CustomLayoutManager layoutManager = new CustomLayoutManager(getActivity());
layoutManager.setSpeed(1500f);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
Then Create CustomLayoutManager to change the speed of 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;
}
}
then in your activity or fragment, create 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);
}
}
};

ZeroOne
- 8,996
- 4
- 27
- 45