CoordinatorLayout和AppBarLayout滑动弹跳(回弹)问题解决

前言:项目中在开发吸顶布局的时候使用了CoordinatorLayout和AppBarLayout实现,布局包括CoordinatorLayout、CollapsingToolbarLayout 、AppBarLayout、ToolBar和RecyclerView这五个类,
但是给CollapsingToolbarLayout 添加了app:layout_scrollFlags=snap属性之后,轻轻滑动的时候在snap阀值的地方会有一个卡顿的过程然后会继续滑动到结束。

1.首先看下xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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">
    <!--AppBarLayout必须设置固定高度-->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/AppFragment_AppBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_behavior="com.boco.whl.funddemo.module.adapter.behavior.WhlBehavior">
        <!--设置可滚动并且折叠在顶部-->
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/AppFragment_CollapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="@color/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7">
            </RelativeLayout>
            <!--设置视差模式-->
            <android.support.v7.widget.Toolbar
                android:id="@+id/AppFragment_Toolbar"
                android:layout_width="match_parent"
                android:layout_height="76dp"
                android:paddingTop="20dp"
                app:layout_collapseMode="pin">
                <!--设置固定在顶部-->
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="56dp">
                </RelativeLayout>
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/MyFragment_recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="20dp"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    <!--RecyclerView滚动行为-->

</android.support.design.widget.CoordinatorLayout>

重点是
1.AppBarLayout中增加如下命名空间:
app:layout_behavior="com.boco.whl.funddemo.module.adapter.behavior.WhlBehavior";
用来解决滑动回弹的bug;
2.CollapsingToolBarLayout中增加如下命名空间:
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap";
(5个scrollFlag关联源码)

* The view will be scroll in direct relation to scroll events. This flag needs to be
* set for any of the other flags to take effect. If any sibling views
* before this one do not have this flag, then this value has no effect.
 public static final int SCROLL_FLAG_SCROLL = 0x1;

* When exiting (scrolling off screen) the view will be scrolled until it is
* 'collapsed'. The collapsed height is defined by the view''s minimum height.
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
 public static final int SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = 0x2;

* When entering (scrolling on screen) the view will scroll on any downwards
* scroll event, regardless of whether the scrolling view is also scrolling. This
* is commonly referred to as the 'quick return' pattern.
public static final int SCROLL_FLAG_ENTER_ALWAYS = 0x4;

* An additional flag for 'enterAlways' which modifies the returning view to
* only initially scroll back to it''s collapsed height. Once the scrolling view has
* reached the end of it''s scroll range, the remainder of this view will be scrolled
* into view. The collapsed height is defined by the view''s minimum height.
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
public static final int SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = 0x8;

* Upon a scroll ending, if the view is only partially visible then it will be snapped
* and scrolled to it''s closest edge. For example, if the view only has it''s bottom 25%
* displayed, it will be scrolled off screen completely. Conversely, if it''s bottom 75% * is visible then it will be scrolled fully into view.
public static final int SCROLL_FLAG_SNAP = 0x10;

用来使ToolBarLayout滑动时有个紧贴效果
3.以及Recyclerview中增加如下命名空间:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
用来绑定和AppBarLayout的联动滚动效果;

2.解题思路:

1.前情提要:


AppBarLayout类结构:.png

其中Behavior类结构:.png

继承关系如下:

1.public static class Behavior extends HeaderBehavior<AppBarLayout>

2.abstract class HeaderBehavior<V extends View> extends ViewOffsetBehavior<V>

3.class ViewOffsetBehavior<V extends View> extends CoordinatorLayout.Behavior<V>

2.在AppBarLayout.Behavior中我们发现这个方法用来实现贴紧效果的

private void snapToChildIfNeeded(CoordinatorLayout coordinatorLayout, AppBarLayout abl) {
            final int offset = getTopBottomOffsetForScrollingSibling();
            final int offsetChildIndex = getChildIndexOnOffset(abl, offset);
            if (offsetChildIndex >= 0) {
                final View offsetChild = abl.getChildAt(offsetChildIndex);
                final LayoutParams lp = (LayoutParams) offsetChild.getLayoutParams();
                final int flags = lp.getScrollFlags();

                if ((flags & LayoutParams.FLAG_SNAP) == LayoutParams.FLAG_SNAP) {
                    // We're set the snap, so animate the offset to the nearest edge
                    int snapTop = -offsetChild.getTop();
                    int snapBottom = -offsetChild.getBottom();

                    if (offsetChildIndex == abl.getChildCount() - 1) {
                        // If this is the last child, we need to take the top inset into account
                        snapBottom += abl.getTopInset();
                    }

                    if (checkFlag(flags, LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED)) {
                        // If the view is set only exit until it is collapsed, we'll abide by that
                        snapBottom += ViewCompat.getMinimumHeight(offsetChild);
                    } else if (checkFlag(flags, LayoutParams.FLAG_QUICK_RETURN
                            | LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)) {
                        // If it's set to always enter collapsed, it actually has two states. We
                        // select the state and then snap within the state
                        final int seam = snapBottom + ViewCompat.getMinimumHeight(offsetChild);
                        if (offset < seam) {
                            snapTop = seam;
                        } else {
                            snapBottom = seam;
                        }
                    }

                    final int newOffset = offset < (snapBottom + snapTop) / 2
                            ? snapBottom
                            : snapTop;
                    animateOffsetTo(coordinatorLayout, abl,
                            MathUtils.clamp(newOffset, -abl.getTotalScrollRange(), 0), 0);
                }
            }
        }

在两个地方执行:

1.
        @Override
        void onFlingFinished(CoordinatorLayout parent, AppBarLayout layout) {
            // At the end of a manual fling, check to see if we need to snap to the edge-child
            snapToChildIfNeeded(parent, layout);
        }
2.
        @Override
        public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl,
                View target, int type) {
            if (type == ViewCompat.TYPE_TOUCH) {
                // If we haven't been flung then let's see if the current view has been set to snap
                snapToChildIfNeeded(coordinatorLayout, abl);
            }
            // Keep a reference to the previous nested scrolling child
            mLastNestedScrollingChildRef = new WeakReference<>(target);
        }

明显我们需要对第二种执行情况进行修改,使得正在滑动的时候不执行贴紧操作,实现方式就是继承Behavior类重写其onStopNestedScroll方法,判断当前是否处于惯性滑动操作之中。

3.自定义Behevior源码如下:
/**
 * @author:honglei92
 * @time:2018/7/26
 */
public class WhlBehavior extends AppBarLayout.Behavior {
    /**
     * 是否处于惯性滑动状态
     */
    private boolean isFlinging = false;
    public WhlBehavior() {}

    public WhlBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
        //如果不是惯性滑动,让他可以执行紧贴操作
        if (!isFlinging) {
            super.onStopNestedScroll(coordinatorLayout, abl, target, type);
        }
    }
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        //type==1时处于非惯性滑动
        if (type == 1) {
            isFlinging = false;
        }
    }
    @Override
    public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull AppBarLayout child, @NonNull View target, float velocityX, float velocityY, boolean consumed) {
        //惯性滑动的时候设置为true
        isFlinging = true;
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }
}

附上执行效果图:


执行效果图.gif

参考:
http://www.georgeyang.cn/blog/read?id=344220025071

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,047评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,807评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,501评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,839评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,951评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,117评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,188评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,929评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,372评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,679评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,837评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,536评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,168评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,886评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,129评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,665评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,739评论 2 351

推荐阅读更多精彩内容