NestedScrollView嵌套RecyclerView,切换页面RecyclerView自动滚到(跳到)NestedScrollView顶部
当NestedScrollView嵌套RecyclerView时候,在页面来回切换时候,比如布局文件这样嵌套写:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/hx_background">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="103dp"
android:background="@android:color/white"
android:orientation="horizontal"></LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:background="@android:color/white"
android:fadingEdgeLength="15dp"
android:requiresFadingEdge="vertical" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
会发现当页面从当前布局且走,再切回来时候,id为linear_layout的LinearLayout线性布局不可见了,而id为recycler_view的RecyclerView却自动滚动到页面的最顶部。若当前布局是二次嵌套在ViewPgaer里面,异常情况更为明显。
原因是NestedScrollView嵌套同为可滚动组件RecyclerView时候,RecyclerView争夺到焦点,触发NestedScrollView滚动到RecyclerView的位置。
解决问题的方案是把NestedScrollView嵌套的第一个有效View(即在本例中被滚出可视区域见不到id为linear_layout的LinearLayout)设置焦点:
android:focusable="true"
android:focusableInTouchMode="true"
最终布局写法:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/hx_background">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="103dp"
android:background="@android:color/white"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="horizontal">
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:background="@android:color/white"
android:fadingEdgeLength="15dp"
android:requiresFadingEdge="vertical" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>