正常情况下,由于NestedScrollView/ScrollView 嵌套RecyclerView,可能会导致Recyclerview占据焦点导致整个NestedScrollView/ScrollView内容上滑。
此问题的解决方案如下:
1、 在根布局设置android:descendantFocusability=”blocksDescendants” ;
android:descendantFocusability 有三种值说明如下:
beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
这种方法,会造成页面中Editext焦点被抢导致无法输入,需要用到第二种方法。
2、对于有Editext的页面需要在根布局使用 :
android:focusable="true"
android:focusableInTouchMode="true"
3、在NestedScrollView/ScrollView顶部第一个控件使用 :
android:focusable="true"
android:focusableInTouchMode="true"
在实际开发中,不建议使用ScrollView包裹ListView/GridView/ExpandableListView,因为这样会把ListView的所有Item都加载到内存中,需要消耗巨大的内存和CPU去绘制画面。推荐使用NestedScrollView。