I wrote a custom ViewPager
to disable Swipe Scroll
, but I want to swipe programmatically. I have three Tab
in my view pager, but when I call viewPager.setCurrentItem(viewPager.getCurrentItem()+1)
on the first Fragment
, it moves to the third Fragment
instead of the second Fragment
. And if I call same function in the second Fragment
, it goes to the third. If I call (viewPager.getCurrentItem()-1)` in the third fragment, it works fine by moving back. Any help would be appreciated. My code is below:
NonSwipeAbleViewPager
public class NonSwipeableViewPager extends ViewPager {
private boolean swipeable;
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPager);
try {
swipeable = a.getBoolean(R.styleable.MyViewPager_swipeable, true);
} finally {
a.recycle();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return swipeable ? super.onInterceptTouchEvent(event) : false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return swipeable ? super.onTouchEvent(event) : false;
}
}
Declaration in XML
<co.example.customview.NonSwipeableViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:swipeable="false" />
Calling it
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuNext:
NonSwipeableViewPager pages = (NonSwipeableViewPager) getActivity().findViewById(R.id.pager);
pages.setCurrentItem(pages.getCurrentItem()+1, true);
break;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…