美文网首页Android-CoordinatorLayout.……
解决CoordinatorLayout+AppBarLayout

解决CoordinatorLayout+AppBarLayout

作者: 一只特立独行的史努比 | 来源:发表于2021-02-23 17:22 被阅读0次

    1.问题描述:

    界面中使用了CoordinatorLayout,AppBarLayout,CollapsingToolbarLayout,ViewPage,RecyclerView,当向上滑动AppBarLayout并在惯性滑动未停止的时候滑动RecyclerView,此时会发生回弹抖动现象

    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抖动问题"
                        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.滑动抖动问题分析

    • CoordinatorLayout向上fling滚动无法被外部中断
    • CoordinatorLayout和子View的联动时通过CoordinatorLayout.Behavior实现的,AppBarLayout使用的Behavior继承了HeaderBehavior。
      问题就在这里。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。

    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:
                    //手指触摸屏幕的时候停止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);
            }
        }
    }
    
    

    应用到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">
    
    

    最终解决问题

    点击跳转demo地址

    相关文章

      网友评论

        本文标题:解决CoordinatorLayout+AppBarLayout

        本文链接:https://www.haomeiwen.com/subject/cpxdfltx.html