Disable swiping between tabs

丶灬走出姿态 提交于 2019-11-28 17:00:02

This answer can be applied to any ViewPager actually no matter what is the library you are using to implement the tabs or even a normal ViewPager without tabs.

The library you are using neokree/MaterialTabs is backed with a ViewPager that is responsible for the swiping effect and you can disable that by providing your own custom ViewPager.

ViewPager with paging disabled all the time

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class CustomViewPager extends ViewPager {

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return false;
    }
}

OR ViewPager with paging switchable to on or off at anytime.

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return enabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return enabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isPagingEnabled() {
        return enabled;
    }
}

This class provides a ViewPager that is swiping enabled and you can turn it off by viewPager.setPagingEnabled(false);

No to mention that you have to change the XML layout to your new custom ViewPager rather than the original one.

<android.support.v4.view.ViewPager 
   ...
   />

to

<my.package.CustomViewPager 
   ...
   />
Reza Nazeri

The simplest way is to setOnTouchListener and return true for ViewPager.

original answer: https://stackoverflow.com/a/13392198/4293813

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!