首页 > 解决方案 > 滚动内容时如何滑动 ViewPager?

问题描述

我可以很好地实现TabLayout,但是当滚动里面的内容(减速动画)时,我不能左右滑动来改变里面的其他片段。我必须等到滚动动画停止然后滑动。ViewPagerViewPagerViewPager

下面是我的一些代码片段。

我有一个简单的activity_main.xml布局,如下所示。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbarHome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"/>

    <LinearLayout
        android:id="@+id/mainContainerLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
    </LinearLayout>

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/btmNavView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:menu="@menu/menu_main" />

</LinearLayout>

然后我将一个包含TabLayout和的片段膨胀ViewPager到. 此布局如下所示:LinearLayoutactivity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.pchatanan.sontana.custom_views.AppTabLayout
        android:id="@+id/contactTabLayout"
        app:tabMode="fixed"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        style="@style/AppTabLayout"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/contactViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

我的片段中的逻辑如下:

fragmentArray = new Fragment[]{new SimpleFragment(), new SimpleFragment(), new SimpleFragment()};
titleArray = new String[]{"fragment1", "fragment2", "fragment3"};

contactPagerAdapter = new AppPagerAdapter(getChildFragmentManager(), fragmentArray, titleArray);
contactViewPager.setAdapter(contactPagerAdapter);
contactViewPager.setOffscreenPageLimit(fragmentArray.length - 1);
contactTabLayout.setupWithViewPager(contactViewPager);

标签: androidandroid-fragmentsandroid-viewpagerandroid-tablayout

解决方案


与@Khemraj 建议的类似,问题是 ViewPager 没有拦截触摸。它只被 ScrollView 拦截。为了解决这个问题,我们应该允许 ViewPage 在滚动时拦截触摸:

scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
    @Override
    public void onScrollChange(View view, int i, int i1, int i2, int i3) {
        viewPager.requestDisallowInterceptTouchEvent(false);
    }
});

更好的实现是在包含滚动视图的片段上使用 CallBackListener。


推荐阅读