TabLayout+ViewPager撤消左右滑动切换功能
时间: 2024-04-25 13:24:25 浏览: 25
要禁用TabLayout与ViewPager的左右滑动切换功能,您可以自定义一个ViewPager的子类,并重写它的 `onInterceptTouchEvent` 方法。
首先,创建一个名为 `NonSwipeableViewPager` 的类,并继承自 ViewPager:
```java
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(@NonNull Context context) {
super(context);
}
public NonSwipeableViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// 返回false,禁止ViewPager的左右滑动切换
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// 返回false,禁止ViewPager的左右滑动切换
return false;
}
}
```
接下来,在您的布局文件中使用 `NonSwipeableViewPager` 替代原来的 ViewPager:
```xml
<com.example.NonSwipeableViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
最后,通过以下方式将 TabLayout 与 NonSwipeableViewPager 绑定:
```java
TabLayout tabLayout = findViewById(R.id.tabLayout);
NonSwipeableViewPager viewPager = findViewById(R.id.viewPager);
// 设置ViewPager的适配器
viewPager.setAdapter(adapter);
// 将TabLayout与ViewPager关联起来
tabLayout.setupWithViewPager(viewPager);
```
这样就可以禁用TabLayout与ViewPager的左右滑动切换功能了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)