天天看點

【Android】ScrollView嵌套RecyclerView,RecyclerView總是把它上面的控件頂出頁面

ScrollView嵌套RecyclerView,當我離開目前頁面,然後又回來時,RecyclerView就會把它上邊的控件都擠出頁面,它顯示在頁面最上邊。

原因應該是RecyclerView搶了焦點,隻需要把ScrollView中最上邊的那個控件加上幾句代碼就可以解決這個問題。

android:focusable="true"
 android:focusableInTouchMode="true" 
           

這個哥們timshinlee提供了一個更簡單的方法,隻需一行代碼就可以搞定。

我們知道,ScrollView下隻能包裹一個控件,是以我們常用ScrollView包裹一個LinearLayout(或RelativeLayout),然後再包裹我們的其他控件(比如RecyclerView等),那一行代碼就寫在LinearLayout(或RelativeLayout)上。

<LinearLayout
            android: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的意思是阻止。

這是參考連結

android:descendantFocusability用法簡析

繼續閱讀