Comprehensive solution for both ViewPager to prevent swiping between tabs, and TabLayout to prevent clicking the tabs when they are disabled.
First created the CustomViewPager and CustomTabLayout classes (inheriting the fuctionality of ViewPager and TabLayout base classes)
// content of CustomViewPager.java
package mypackage;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;
public class CustomViewPager extends ViewPager {
private boolean enableSwipe;
public CustomViewPager(Context context) {
super(context);
init();
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
enableSwipe = true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return enableSwipe && super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return enableSwipe && super.onTouchEvent(event);
}
public void setEnableSwipe(boolean enableSwipe) {
this.enableSwipe = enableSwipe;
}
}
// content of CustomTabLayout.java
package mypackage;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.google.android.material.tabs.TabLayout;
public class CustomTabLayout extends TabLayout {
private boolean enableTabs;
public CustomTabLayout(Context context) {
super(context);
init();
}
public CustomTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
enableTabs = true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return !enableTabs;
}
public void setEnableTabs(boolean enable) {
this.enableTabs = enable;
}
}
create the UI:
<mypackage.CustomTabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<mypackage.CustomViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
in the onCreate create the relation between the two controls:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
CustomTabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
EnableControls function to enable/disable the tab:
private void EnableControls(boolean b) {
CustomViewPager viewPager = findViewById(R.id.view_pager);
CustomTabLayout tabs = findViewById(R.id.tabs);
viewPager.setEnableSwipe(b);
tabs.setEnableTabs(b);
}