1. 程式人生 > >關於viewpager不顯示內容,Recycleview搶焦點

關於viewpager不顯示內容,Recycleview搶焦點

      有兩個問題,在此記錄一下

      第一個:對於NestedScrollView中巢狀viewpager,若果viewpager的寬和高設定為自適應的話,則viewpager中的內容不顯示;viewpager需要設定固定的高度值,顯示viewpager中的fragment;若不想給viewpager設定固定的值,又想顯示viewpager的內容,則需要重寫viewpager

重寫ViewPager

package com.kongqw.kbox.view;import android.content.Context;import android.support.v4.view.ViewPager;
import android.util.AttributeSet;import android.view.View;publicclassWrapContentHeightViewPagerextendsViewPager { publicWrapContentHeightViewPager(Context context) { super(context); } publicWrapContentHeightViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override
protectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, 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); }}
使用時,直接使用NestedScrollview 包裹 WrapContentHeightViewPager 佈局效果:第二個問題:ScrollView巢狀Recycleview,當我離開當前頁面,然後又回來時,Recycleview就會把它上邊的控制元件擠出頁面,它(recycleview)顯示在頁面最上面。原因是:焦點問題,Recycleview搶了焦點,只需要把scrollview中最上面的那幾個控制元件加上幾句程式碼就可以解決這個問題android:focusable="true"android:focusableInTouchMode="true"
還有一個更簡單的方法,只需一行程式碼搞定我們知道,ScrollView 下只能包裹一個控制元件,所以我們常用Scrollview 包裹一個Linearlayout(或者RelativeLayout),然後再包裹我們的其他控制元件(比如 Recycleview),那一行程式碼就寫在LinearLayout(或者Recycleview中)<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:descendantFocusability="blocksDescendants"android:orientation="vertical">

只寫一行:Android:descendantFocusability=”blocksDescendants”

就可以解決RecyclerView搶焦點,把它上面的控制元件頂飛的bug了。

關於android:descendantFocusability,下面寫點擴充套件知識。

Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Must be one of the following constant values.

該屬性是當一個為view獲取焦點時,定義viewGroup和其子控制元件兩者之間的關係。

屬性的值有三種:

    beforeDescendants:viewgroup會優先其子類控制元件而獲取到焦點

    afterDescendants:viewgroup只有當其子類控制元件不需要獲取焦點時才獲取焦點

    blocksDescendants:viewgroup會覆蓋子類控制元件而直接獲得焦點

本來我以為beforeDescendants也可以起作用,可事實證明我還是太天真了,只能用block,block的意思是阻止。

參考連結:

http://blog.csdn.net/yingpaixiaochuan/article/details/53190420

http://www.jianshu.com/p/28e4346a41cf