ScrollView,SwipeRefreshLayout嵌套RecyclerView时,当离开页面又回来,或者做RecyclerView展开收缩总会把第一个item顶出头部(部分or整个),原因是RecyclerView抢了焦点。知道原因就好办了!多方查找,给出两个解决方案。
方案一:把ScrollView,SwipeRefreshLayout最上边的那个控件加上几句代码。
android:focusable="true"
android:focusableInTouchMode="true"
方案二:timshinlee提供了一个更简单的方法
ScrollView、SwipeRefreshLayout下只能包裹一个控件,所以我们常包裹一个LinearLayout(或RelativeLayout),然后再包裹我们的其他控件(比如RecyclerView等),那一行代码就写在LinearLayout(或RelativeLayout)上。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
推荐使用方案二,简单明了!
关于android:descendantFocusabilityAPI描述如下:
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.
属性的值有三种:
beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
参考链接: