如何在ViewPager中滚动RecyclerView?

时间:2016-11-29 09:58:57

标签: android android-viewpager android-recyclerview

我在ViewPager中有两个标签,每个标签包含一个基本垂直的ListViews的RecyclerView。我的问题是我不能垂直滚动RecyclerViews。

 <com.myapplication.MyViewPager
    android:layout_below="@+id/music_tabs"
    android:id="@+id/music_switcher"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">



        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_featured_music"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_device_music"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</com.myapplication.MyViewPager>

这是MyViewPager

public class MyViewPager extends ViewPager {

public MyViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int height = 0;
    for(int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int h = child.getMeasuredHeight();
        if(h > height) height = h;
    }

    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

2 个答案:

答案 0 :(得分:1)

您无法预先测量recyclerview的大小。正如预期的那样,删除onMeasure后它应该可以正常工作。

答案 1 :(得分:0)

当您使用两个recycleview时,布局高度是换行内容而不是使用此代码或在dp中定义layout_height:

android:layout_height="250dp"