我的佈局可能不是很好,但是卻可能對自己以後碰到或者有類似的場景的朋友們有所幫助,所以下面:
場景一: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);
}
}