解決CoordinatorLayout+AppBarLayout 滑動(dòng)抖動(dòng)問題

1.問題描述:

界面中使用了CoordinatorLayout,AppBarLayout,CollapsingToolbarLayout,ViewPage,RecyclerView,當(dāng)向上滑動(dòng)AppBarLayout并在慣性滑動(dòng)未停止的時(shí)候滑動(dòng)RecyclerView,此時(shí)會發(fā)生回彈抖動(dòng)現(xiàn)象

XML布局代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/c_f2f2f2"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:background="@color/c_f2f2f2"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll"
            android:fitsSystemWindows="true"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/c_f2f2f2"
                android:orientation="vertical"
                app:layout_scrollFlags="scroll">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:background="#ff0000"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:text="AppBarLayout抖動(dòng)問題"
                    android:textColor="@color/white"
                    android:textSize="20sp"
                    android:textStyle="bold" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="120dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:background="#de3f7c" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="190dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="10dp"
                    android:background="#ea7293" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="370dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="10dp"
                    android:background="#1a94bc" />

            </LinearLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>


        <View
            android:layout_width="match_parent"
            android:layout_height="10dp"
            android:background="@color/c_f2f2f2" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/magicindicator"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="10dp"
            android:background="@color/c_f2f2f2" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="12dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


2.滑動(dòng)抖動(dòng)問題分析

  • CoordinatorLayout向上fling滾動(dòng)無法被外部中斷
  • CoordinatorLayout和子View的聯(lián)動(dòng)時(shí)通過CoordinatorLayout.Behavior實(shí)現(xiàn)的,AppBarLayout使用的Behavior繼承了HeaderBehavior。
    問題就在這里。HeaderBehavior的onTouchEvent中使用Scroller實(shí)現(xiàn)了fling操作,但是沒有通過NestedScrolling API對外開放,也就說一旦HeaderBehavior的fling動(dòng)作形成,無法由外部主動(dòng)中斷。
    RecyclerView向下fling滾動(dòng)
    與AppBarLayout同層級的RecyclerView可以通過升級過的NestedScrolling API對AppBarLayout產(chǎn)生影響,比如RecyclerView向下fling時(shí)滑動(dòng)到item 0之后,如果AppBarLayout可以滑動(dòng)時(shí)會給AppBarLayout施加一個(gè)同樣向下的fling動(dòng)作,以此形成一個(gè)連貫的下滑fling。
    那么問題來了。當(dāng)HeaderBehavior產(chǎn)生的向上的fling沒有結(jié)束時(shí),RecyclerView又送來向下的fling,抖動(dòng)就產(chǎn)生了。
    分析一下HeaderBehavior
    當(dāng)檢測到down事件時(shí), 取消了mScroller的運(yùn)行(如果它正在scroll的話)。這里因?yàn)橐L問父類(其實(shí)是父類的父類)的 mScroller變量。
    然后通過反射拿到mScroller變量,在onInterceptTouchEvent攔截事件中,當(dāng)手指離開的時(shí)候,則停止overScroller動(dòng)畫效果。
    然后通過反射拿到flingRunnable變量,在onInterceptTouchEvent攔截事件中,當(dāng)手指離開的時(shí)候,則需要remove所有的flingRunnable。

3.解決問題

自定義AppBarLayout.Behavior

/**
 * description:AppBarLayoutBehavior
 * Author: 許少東
 */
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:
                //手指觸摸屏幕的時(shí)候停止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時(shí),表示當(dāng)前target處于非touch的滑動(dòng),
        //該bug的引起是因?yàn)閍ppbar在滑動(dòng)時(shí),CoordinatorLayout內(nèi)的實(shí)現(xiàn)NestedScrollingChild2接口的滑動(dòng)
        //子類還未結(jié)束其自身的fling
        //所以這里監(jiān)聽子類的非touch時(shí)的滑動(dòng),然后block掉滑動(dòng)事件傳遞給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);
        }
    }
}


應(yīng)用到AppBarLayout

<com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:background="@color/c_f2f2f2"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        app:layout_behavior=".wight.AppBarLayoutBehavior"
        android:layout_height="wrap_content">

最終解決問題

點(diǎn)擊跳轉(zhuǎn)demo地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容