Temporarily/dynamically Disable Single Page In Viewpager
I have an extended FragmentPagerAdapter that provides 3 fragments to a ViewPager, giving me 3 pages that I can either swipe between or use the tabs I've added to the actionbar to m
Solution 1:
You're definitely going to want to create your own custom ViewPager subclass. I created a simple custom ViewPager
called CustomSwipePager
that will handle blocking user interaction when needed.
publicclassCustomSwipeViewPagerextendsViewPager {
privatebooleanmLastPageEnabled=false;
privateintmLastPageIndex=0;
publicNoSwipeViewPager(Context context) {
super(context);
}
publicNoSwipeViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
publicvoidsetLastPageEnabled(boolean enabled) {
mLastPageEnabled = enabled;
}
publicvoidsetLastPageIndex(int index) {
mLastPageIndex = index;
}
@OverridepublicbooleanonInterceptTouchEvent(MotionEvent event){
if(!mLastPageEnabled && getCurrentItem() >= (mLastPageIndex - 1)) {
// Always return false to disable user swipesreturnfalse;
}
returntrue;
}
@OverridepublicbooleanonTouchEvent(MotionEvent event) {
if (!mLastPageEnabled && getCurrentItem() >= (mLastPageIndex - 1)) {
// Always return false to disable user swipesreturnfalse;
}
returntrue;
}
}
There are two key methods you will want to take advantage of in the class setLastPageEnabled()
and setLastPageIndex()
. You can set the last page index to whatever you need, in your case if you have three items you would set it to 2. Then also use setLastPageEnabled(false)
to disable swiping or to re-enabled use setLastPageEnabled(true)
.
You can include this custom view into your layout like this:
<com.mypackage.CustomSwipeViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_swipe_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And finally reference it in your Fragment or Activity in the appropriate place:
privateCustomSwipeViewPager mPager;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mPager = (CustomSwipeViewPager) findViewById(R.id.custom_swipe_view_pager);
mPager.setLastPageEnabled(false);
mPager.setLastPageIndex(2);
}
Post a Comment for "Temporarily/dynamically Disable Single Page In Viewpager"