情景
開發(fā)過程中状植,經常會遇到ScrollView嵌套RecyclerView。但是實際操作后驳遵,會發(fā)現拖動RecyclerView時淫奔,會有或多或少的卡頓,這種便是滑動沖突堤结。在此之前唆迁,經歷過ScrollView嵌套ScrollView滑動沖突鸭丛,ScrollView與ListView嵌套滑動沖突等等,網上解決方法比較多暫不贅述了唐责,RecyclerView出來已經差不多4年了鳞溉,ListView可以說已經成為了過去式了,現在開發(fā)完全使用RecyclerView就行了鼠哥。
解決方案:NestedScrollView+RecyclerView優(yōu)雅的解決滑動沖突問題
我親自試驗過熟菲,RecyclerView嵌套RecyclerView是不存在滑動沖突的,ScrollView嵌套RecyclerView也會存在顯示不全的問題朴恳,滑動也有一點點粘連的感覺不是太流暢抄罕,NestedScrollView嵌套RecyclerView不會存在顯示不全的問題,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
上面的代碼只是簡單的嵌套而已菜皂,但是還有一個小問題贞绵,觸摸到RecyclerView的時候滑動還有些粘連的感覺,只需要在代碼中設置
mRecyclerView.setNestedScrollingEnabled(false);
就可以完美的解決這個問題恍飘。
新的問題
關于NestedScrollView + RecyclerView頁面載入時總是滑動到最底部
解決方案
項目中遇到頁面載入時總是滑動到最底部榨崩,原因是焦點在頁面底部;解決方法就是在根布局設置
android:descendantFocusability="blocksDescendants" 章母;
android:descendantFocusability 有三種值:
beforeDescendants:viewgroup會優(yōu)先其子類控件而獲取到焦點
afterDescendants:viewgroup只有當其子類控件不需要獲取焦點時才獲取焦點
blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點