androidandroid-layoutandroid-fragmentsfragmentpageradapterandroid-pageradapter

Disable swipe in fragmentPagerAdapter? - android


I have a fragmentPagerAdapter with 3 fragments in it. How would I disable the swiping between the 3 fragments so the user only uses the tabview to go between fragments?

private class ViewPagerAdapter extends FragmentPagerAdapter
{
    ArrayList<Fragment> fragments = new ArrayList<>();
    ArrayList<String> tabTitles = new ArrayList<>();

    public ViewPagerAdapter(android.support.v4.app.FragmentManager fragmentManager)
    {
        super(fragmentManager);
    }
    @Override
    public Fragment getItem(int position)
    {
        return fragments.get(position);
    }
    @Override
    public int getCount()
    {
        return fragments.size();
    }
    @Override
    public CharSequence getPageTitle(int position)
    {
        return tabTitles.get(position);
    }
    public void addFragments(Fragment fragment, String titles)
    {
        this.fragments.add(fragment);
        this.tabTitles.add(titles);
    }
}

Solution

  • You can setup a custom view pager like this :-

    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;
        }
    }
    

    And then in the layout you can set it as :-

    <mypackage.lockableviewpager 
        android:id="@+id/photosViewPager" 
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>
    

    And then just call

    setSwipeable(false)
    

    Hope it helps.