Reputation: 33
My program has a boolean variable name "isCorrect". I want, when isCorrect is false then the user should not able to open any other tab. (Either by swiping or by selecting tab). I tried to do this by below given logic but this cause the application to hang.
final boolean isCorrect=false;
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(!isCorrect){
if(tab.getPosition()==1){
mViewPager.setCurrentItem(0);
}
}else{
mViewPager.setCurrentItem(1);
}
}
Upvotes: 1
Views: 330
Reputation: 5302
Define a custom ViewPager subclass. The class inherits from ViewPager and includes a new method called setSwipeable to control if swipe events are enabled or not. Make sure to change layout file.
public class LockableViewPager extends ViewPager {
private boolean swipeable;
public LockableViewPager(Context context) {
super(context);
}
public LockableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.swipeable = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.swipeable) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.swipeable) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setSwipeable(boolean swipeable) {
this.swipeable = swipeable;
}
}
When flag is false disable swipe.
if (!flag) {
mViewPager.setSwipeable(false);
} else {
mViewPager.setSwipeable(true);
}
Upvotes: 1