我的布局可能不是很好,但是却可能对自己以后碰到或者有类似的场景的朋友们有所帮助,所以下面:
场景一:ViewPager+Fragment切换时,RecyclerView向上自动滑动
解决方案:禁止RecyclerView获取焦点,在父布局中加入
android:descendantFocusability="blocksDescendants"
完整代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_hot"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
这样就可以解决在Fragment中有RecyclerView时,ViewPager切换就不会自动滑动的情况
场景二:ScrollView中嵌套ViewPager时,同时内部的数据层用的RecyclerView,这种嵌套导致adapter中的数据无法加载出来,列表页为空
解决方案:ScrollView中加入属性 ,代码如下
android:fillViewport="true"
目的是为了让ViewPager中显示出来数据,这样就解决了ViewPager中无数据的情况
场景三:ViewPager嵌套了Fragment,Fragment里有Recyclerview,ScrollView没法滑动
解决方案1:把滑动事件都交给外层的ScrollView处理,禁止RecyclerView滑动功能,步骤如下
1、设置 recyclerView.setNestedScrollingEnabled(false);//限制recyclerview自身滑动特性,滑动全部靠scrollview完成
2、recyclerview的布局里添加
android:focusableInTouchMode="true"
android:focusable="true"
解决方案2:自定义ViewPager,之所以无法滚动是因为下面的控件高度没有取到,故重写onMeasure()方法计算高度即可,代码如下
(注:不要重写onInterceptTouchEvent()方法,会拦截掉RecyclerView中的item的点击事件,使列表中失去焦点无法点击)
public class PersonalViewpager extends ViewPager {
public PersonalViewpager(Context context) {
super(context);
}
public PersonalViewpager(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);
}
}