Custom PagerTabStrip how to disable switching tabs via click - Not Working

1k views Asked by At

I want to disable the "switching tabs by clicking on tab name" of the PagerTabStrip based on a condition.

I think the following code is right but I am still able to switch tabs by clicking on the tab names. I was able to disable the switching of tabs via swipe by custom ViewPager but I want to disable by clicking on tab names too.

My custom PagerTabStrip

package com.blah;

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

public class CustomPagerTabStrip extends PagerTabStrip {

    private boolean isTabSwitchEnabled;

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        System.out.println("ENable?? "+isTabSwitchEnabled); // it prints out false or true based on what I have set
        if (this.isTabSwitchEnabled) {
            return super.onInterceptTouchEvent(event);
        } else {
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.isTabSwitchEnabled) {
            return super.onTouchEvent(event);
        }
        return false;
    }

    public void setTabSwitchEnabled(boolean isSwipeEnabled) {
        this.isTabSwitchEnabled = isSwipeEnabled;
    }
}

I disable it by using:

CustomPagerTabStrip pagerTabStrip = (CustomPagerTabStrip) findViewById(R.id.tabtitle);
pagerTabStrip.setTabSwitchEnabled(false);

My layout:

<com.blah.CustomViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.blah.CustomPagerTabStrip
            android:id="@+id/tabtitle"
            style="@style/viepagertitlestrip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@color/primary"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            >

        </com.blah.CustomPagerTabStrip>
    </com.blah.CustomViewPager>
1

There are 1 answers

0
Kasun Dissanayake On BEST ANSWER

Consume the touch event in onInterceptTouchEvent() by returning true. I think it will do the job

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    System.out.println("ENable?? "+isTabSwitchEnabled); // it prints out false or true based on what I have set
    if (this.isTabSwitchEnabled) {
        return super.onInterceptTouchEvent(event);
    } else {
        return true;
    }
}