如何将 Listview 和 Viewpager 放在 ScrollView 中?

How to place Listview and Viewpager inside a ScrollView?

我有一个 listview 和 viewpager,我用它们来生成我的图像滑块。这两个有自己的适配器。在我的 layout.xml 中,我想将它们放入滚动视图中,但是当我这样做时,viewpager 不会与列表视图一起滚动。有什么想法可以帮帮我吗?

谢谢

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.test.MainActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/test">

            <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/pager_news"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />

            <ListView
                android:id="@+id/news_lw"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="2"
                android:nestedScrollingEnabled="true">

            </ListView>
        </LinearLayout>

    </LinearLayout>

ListView 不支持嵌套滚动。因此,如果您认为这种行为是必要的,请改用 NestedScrollViewRecyclerView

更好的方法是使用 CoordinatorLayout 并定义一个自定义行为,如果 RecyclerView 滚动到特定范围,则将 ViewPager 滚动进或出。

使用 NestedScrollViewRecyclerView 而不是 ListView

试试这个:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/test">

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

        <android.support.v7.widget.RecyclerView
            android:id="@+id/news_lw"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/pager_news">

        </android.support.v7.widget.RecyclerView>
    </RelativeLayout>

</android.support.v4.widget.NestedScrollView>