CoordinatorLayout滑動抖動問題

目錄介紹

  • 01.CoordinatorLayout滑動抖動問題描述
  • 02.滑動抖動問題分析
  • 03.自定義AppBarLayout.Behavior說明
  • 04.CoordinatorLayout滑動抖動解決方案
  • 05.案例測試是否根本問題

好消息

  • 博客筆記大彙總【16年3月到至今】,包括Java基礎及深入知識點,Android技術博客,Python學習筆記等等,還包括平時開發中遇到的bug彙總,當然也在工作之餘收集了大量的面試題,長期更新維護並且修正,持續完善……開源的文件是markdown格式的!同時也開源了生活博客,從12年起,積累共計N篇[近100萬字,陸續搬到網上],轉載請註明出處,謝謝!
  • 鏈接地址:https://github.com/yangchong2...
  • 如果覺得好,可以star一下,謝謝!當然也歡迎提出建議,萬事起於忽微,量變引起質變!

01.CoordinatorLayout滑動抖動問題描述

  • 先看下佈局

    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/coordinator"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
    
        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <!--這個是滾動頭部-->
            <include layout="@layout/include_find_header"/>
    
            <!--這個是吸頂佈局-->
            <include layout="@layout/include_sticky_header"/>
    
        </android.support.design.widget.AppBarLayout>
    
        <!--app:layout_behavior 屬性,該佈局包含一個豎直方向的RecyclerView-->
        <include layout="@layout/include_recycler_view" />
    
    </android.support.design.widget.CoordinatorLayout>
  • 出現的問題

    • 用手指輕輕滑動CoordinatorLayout部分, 上滑, 快速擡起手指, 形成一個fling操作。其實就是向上滑動一下!
    • 這時, 整個CoordinatorLayout部分會向上移動(fling),在停止移動之前,在下面的區域(也就是xml佈局中的include_recycler_view)來一個反向的滑動(fling) , 這時整個頁面就會開始或大或小的抖動, 非常明顯。

02.滑動抖動問題分析

  • CoordinatorLayout向上fling滾動無法被外部中斷

    • CoordinatorLayout和子View的聯動時通過CoordinatorLayout.Behavior實現的,AppBarLayout使用的Behavior繼承了HeaderBehavior<AppBarLayout>。
    • 問題就在這裏。HeaderBehavior的onTouchEvent中使用Scroller實現了fling操作,但是沒有通過NestedScrolling API對外開放,也就說一旦HeaderBehavior的fling動作形成,無法由外部主動中斷。
  • RecyclerView向下fling滾動

    • 與AppBarLayout同層級的RecyclerView可以通過升級過的NestedScrolling API對AppBarLayout產生影響,比如RecyclerView向下fling時滑動到item 0之後,如果AppBarLayout可以滑動時會給AppBarLayout施加一個同樣向下的fling動作,以此形成一個連貫的下滑fling。
    • 那麼問題來了。當HeaderBehavior產生的向上的fling沒有結束時,RecyclerView又送來向下的fling,抖動就產生了。
  • 分析一下HeaderBehavior

    • 當檢測到down事件時, 取消了mScroller的運行(如果它正在scroll的話)。這裏因爲要訪問父類(其實是父類的父類)的 mScroller變量。
    • 然後通過反射拿到mScroller變量,在onInterceptTouchEvent攔截事件中,當手指離開的時候,則停止overScroller動畫效果。
    • 然後通過反射拿到flingRunnable變量,在onInterceptTouchEvent攔截事件中,當手指離開的時候,則需要remove所有的flingRunnable。

03.自定義AppBarLayout.Behavior說明

  • AppBarLayout簡單說明

    • AppBarLayout是一個vertical的LinearLayout,實現了很多material的概念,主要是跟滑動相關的。AppBarLayout的子view需要提供layout_scrollFlags參數。AppBarLayout和CoordinatorLayout強相關,一般作爲CoordinatorLayout的子類,配套使用。
按我的理解,AppBarLayout內部有2種view,一種可滑出(屏幕),另一種不可滑出,根據app:layout_scrollFlags區分。一般上邊放可滑出的下邊放不可滑出的。
  • AppBarLayout.Behavior部分方法說明

    • onInterceptTouchEvent():是否攔截觸摸事件
    • onTouchEvent():處理觸摸事件
    • layoutDependsOn():確定使用Behavior的View要依賴的View的類型
    • onDependentViewChanged():當被依賴的View狀態改變時回調
    • onDependentViewRemoved():當被依賴的View移除時回調
    • onMeasureChild():測量使用Behavior的View尺寸
    • onLayoutChild():確定使用Behavior的View位置
    • onStartNestedScroll():嵌套滑動開始(ACTION_DOWN),確定Behavior是否要監聽此次事件
    • onStopNestedScroll():嵌套滑動結束(ACTION_UP或ACTION_CANCEL)
    • onNestedScroll():嵌套滑動進行中,要監聽的子 View的滑動事件已經被消費
    • onNestedPreScroll():嵌套滑動進行中,要監聽的子 View將要滑動,滑動事件即將被消費(但最終被誰消費,可以通過代碼控制)
    • onNestedFling():要監聽的子 View在快速滑動中
    • onNestedPreFling():要監聽的子View即將快速滑動

04.CoordinatorLayout滑動抖動解決

  • 通過反射拿到flingRunnable變量,注意這裏我判斷了一下27和28版本的問題,27及以下是mFlingRunnable,28及以上是flingRunnable,一定要注意這個問題。

    /**
     * 反射獲取私有的flingRunnable 屬性,考慮support 28以後變量名修改的問題
     * @return Field
 */
private Field getFlingRunnableField() throws NoSuchFieldException {
    Class<?> superclass = this.getClass().getSuperclass();
    try {
        // support design 27及一下版本
        Class<?> headerBehaviorType = null;
        if (superclass != null) {
            String name = superclass.getName();
            LogUtil.d("AppBarLayout.Behavior父類",name);
            headerBehaviorType = superclass.getSuperclass();
        }
        if (headerBehaviorType != null) {
            String name = headerBehaviorType.getName();
            LogUtil.d("AppBarLayout.Behavior父類的父類1",name);
            return headerBehaviorType.getDeclaredField("mFlingRunnable");
        }else {
            return null;
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
        // 可能是28及以上版本
        Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
        if (headerBehaviorType != null) {
            String name = headerBehaviorType.getName();
            LogUtil.d("AppBarLayout.Behavior父類的父類2",name);
            return headerBehaviorType.getDeclaredField("flingRunnable");
        } else {
            return null;
        }
    }
}
```
  • 通過反射拿到scroller變量,和上面類似。

    /**
     * 反射獲取私有的scroller 屬性,考慮support 28以後變量名修改的問題
     * @return Field
 */
private Field getScrollerField() throws NoSuchFieldException {
    Class<?> superclass = this.getClass().getSuperclass();
    try {
        // support design 27及一下版本
        Class<?> headerBehaviorType = null;
        if (superclass != null) {
            headerBehaviorType = superclass.getSuperclass();
        }
        if (headerBehaviorType != null) {
            return headerBehaviorType.getDeclaredField("mScroller");
        }else {
            return null;
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
        // 可能是28及以上版本
        Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
        if (headerBehaviorType != null) {
            return headerBehaviorType.getDeclaredField("scroller");
        }else {
            return null;
        }
    }
}
```
  • 然後在onInterceptTouchEvent攔截事件裏處理邏輯。當手指觸摸屏幕的時候停止fling事件

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        LogUtil.d(TAG, "onInterceptTouchEvent:" + child.getTotalScrollRange());
        shouldBlockNestedScroll = isFlinging;
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                //手指觸摸屏幕的時候停止fling事件
                stopAppbarLayoutFling(child);
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(parent, child, ev);
    }
    
    /**
     * 停止appbarLayout的fling事件
 */
private void stopAppbarLayoutFling(AppBarLayout appBarLayout) {
    //通過反射拿到HeaderBehavior中的flingRunnable變量
    try {
        Field flingRunnableField = getFlingRunnableField();
        Field scrollerField = getScrollerField();
        if (flingRunnableField != null) {
            flingRunnableField.setAccessible(true);
        }
        if (scrollerField != null) {
            scrollerField.setAccessible(true);
        }
        Runnable flingRunnable = null;
        if (flingRunnableField != null) {
            flingRunnable = (Runnable) flingRunnableField.get(this);
        }
        OverScroller overScroller = null;
        if (scrollerField != null) {
            overScroller = (OverScroller) scrollerField.get(this);
        }
        //下面是關鍵點
        if (flingRunnable != null) {
            LogUtil.d(TAG, "存在flingRunnable");
            appBarLayout.removeCallbacks(flingRunnable);
            flingRunnableField.set(this, null);
        }
        if (overScroller != null && !overScroller.isFinished()) {
            overScroller.abortAnimation();
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
```
  • 完整版本的代碼如下所示

    /**
     * <pre>
     *     @author yangchong
     *     blog  : https://github.com/yangchong211
     *     time  : 2019/03/13
     *     desc  : 自定義Behavior
     *     revise: 解決appbarLayout若干問題
     *              1)快速滑動appbarLayout會出現回彈
     *              2)快速滑動appbarLayout到摺疊狀態下,立馬下滑,會出現抖動的問題
     *              3)滑動appbarLayout,無法通過手指按下讓其停止滑動
 */
public class AppBarLayoutBehavior extends AppBarLayout.Behavior {

    private static final String TAG = "AppbarLayoutBehavior";
    private static final int TYPE_FLING = 1;
    private boolean isFlinging;
    private boolean shouldBlockNestedScroll;

    public AppBarLayoutBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        LogUtil.d(TAG, "onInterceptTouchEvent:" + child.getTotalScrollRange());
        shouldBlockNestedScroll = isFlinging;
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                //手指觸摸屏幕的時候停止fling事件
                stopAppbarLayoutFling(child);
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(parent, child, ev);
    }

    /**
     * 反射獲取私有的flingRunnable 屬性,考慮support 28以後變量名修改的問題
     * @return Field
     * @throws NoSuchFieldException
     */
    private Field getFlingRunnableField() throws NoSuchFieldException {
        Class<?> superclass = this.getClass().getSuperclass();
        try {
            // support design 27及一下版本
            Class<?> headerBehaviorType = null;
            if (superclass != null) {
                headerBehaviorType = superclass.getSuperclass();
            }
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("mFlingRunnable");
            }else {
                return null;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            // 可能是28及以上版本
            Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("flingRunnable");
            } else {
                return null;
            }
        }
    }

    /**
     * 反射獲取私有的scroller 屬性,考慮support 28以後變量名修改的問題
     * @return Field
     * @throws NoSuchFieldException
     */
    private Field getScrollerField() throws NoSuchFieldException {
        Class<?> superclass = this.getClass().getSuperclass();
        try {
            // support design 27及一下版本
            Class<?> headerBehaviorType = null;
            if (superclass != null) {
                headerBehaviorType = superclass.getSuperclass();
            }
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("mScroller");
            }else {
                return null;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            // 可能是28及以上版本
            Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("scroller");
            }else {
                return null;
            }
        }
    }

    /**
     * 停止appbarLayout的fling事件
     * @param appBarLayout
     */
    private void stopAppbarLayoutFling(AppBarLayout appBarLayout) {
        //通過反射拿到HeaderBehavior中的flingRunnable變量
        try {
            Field flingRunnableField = getFlingRunnableField();
            Field scrollerField = getScrollerField();
            if (flingRunnableField != null) {
                flingRunnableField.setAccessible(true);
            }
            if (scrollerField != null) {
                scrollerField.setAccessible(true);
            }
            Runnable flingRunnable = null;
            if (flingRunnableField != null) {
                flingRunnable = (Runnable) flingRunnableField.get(this);
            }
            OverScroller overScroller = (OverScroller) scrollerField.get(this);
            if (flingRunnable != null) {
                LogUtil.d(TAG, "存在flingRunnable");
                appBarLayout.removeCallbacks(flingRunnable);
                flingRunnableField.set(this, null);
            }
            if (overScroller != null && !overScroller.isFinished()) {
                overScroller.abortAnimation();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child,
                                       View directTargetChild, View target,
                                       int nestedScrollAxes, int type) {
        LogUtil.d(TAG, "onStartNestedScroll");
        stopAppbarLayoutFling(child);
        return super.onStartNestedScroll(parent, child, directTargetChild, target,
                nestedScrollAxes, type);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout,
                                  AppBarLayout child, View target,
                                  int dx, int dy, int[] consumed, int type) {
        LogUtil.d(TAG, "onNestedPreScroll:" + child.getTotalScrollRange()
                + " ,dx:" + dx + " ,dy:" + dy + " ,type:" + type);
        //type返回1時,表示當前target處於非touch的滑動,
        //該bug的引起是因爲appbar在滑動時,CoordinatorLayout內的實現NestedScrollingChild2接口的滑動
        //子類還未結束其自身的fling
        //所以這裏監聽子類的非touch時的滑動,然後block掉滑動事件傳遞給AppBarLayout
        if (type == TYPE_FLING) {
            isFlinging = true;
        }
        if (!shouldBlockNestedScroll) {
            super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        }
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child,
                               View target, int dxConsumed, int dyConsumed, int
            dxUnconsumed, int dyUnconsumed, int type) {
        LogUtil.d(TAG, "onNestedScroll: target:" + target.getClass() + " ,"
                + child.getTotalScrollRange() + " ,dxConsumed:"
                + dxConsumed + " ,dyConsumed:" + dyConsumed + " " + ",type:" + type);
        if (!shouldBlockNestedScroll) {
            super.onNestedScroll(coordinatorLayout, child, target, dxConsumed,
                    dyConsumed, dxUnconsumed, dyUnconsumed, type);
        }
    }

    @Override
    public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl,
                                   View target, int type) {
        LogUtil.d(TAG, "onStopNestedScroll");
        super.onStopNestedScroll(coordinatorLayout, abl, target, type);
        isFlinging = false;
        shouldBlockNestedScroll = false;
    }

    private static class LogUtil{
        static void d(String tag, String string){
            Log.d(tag,string);
        }
    }

}
```

05.案例測試是否根本問題

  • 代碼如下所示

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        app:layout_behavior="org.yczbj.ycrefreshview.sticky.AppBarLayoutBehavior"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  • 發現最終解決問題

06.參考案例

其他介紹

01.關於博客彙總鏈接

02.關於我的博客

項目地址:https://github.com/yangchong2...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章