CoordinatorLayout和AppBarLayout滑動(dòng)彈跳(回彈)問題解決

前言:項(xiàng)目中在開發(fā)吸頂布局的時(shí)候使用了CoordinatorLayout和AppBarLayout實(shí)現(xiàn),布局包括CoordinatorLayout、CollapsingToolbarLayout 、AppBarLayout、ToolBar和RecyclerView這五個(gè)類,
但是給CollapsingToolbarLayout 添加了app:layout_scrollFlags=snap屬性之后,輕輕滑動(dòng)的時(shí)候在snap閥值的地方會(huì)有一個(gè)卡頓的過程然后會(huì)繼續(xù)滑動(dòng)到結(jié)束。

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必須設(shè)置固定高度-->
    <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">
        <!--設(shè)置可滾動(dòng)并且折疊在頂部-->
        <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>
            <!--設(shè)置視差模式-->
            <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">
                <!--設(shè)置固定在頂部-->
                <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滾動(dòng)行為-->

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

重點(diǎn)是
1.AppBarLayout中增加如下命名空間:
app:layout_behavior="com.boco.whl.funddemo.module.adapter.behavior.WhlBehavior";
用來(lái)解決滑動(dòng)回彈的bug;
2.CollapsingToolBarLayout中增加如下命名空間:
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap";
(5個(gè)scrollFlag關(guān)聯(lián)源碼)

* 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;

用來(lái)使ToolBarLayout滑動(dòng)時(shí)有個(gè)緊貼效果
3.以及Recyclerview中增加如下命名空間:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
用來(lái)綁定和AppBarLayout的聯(lián)動(dòng)滾動(dòng)效果;

2.解題思路:

1.前情提要:


AppBarLayout類結(jié)構(gòu):.png

其中Behavior類結(jié)構(gòu):.png

繼承關(guān)系如下:

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中我們發(fā)現(xiàn)這個(gè)方法用來(lái)實(shí)現(xiàn)貼緊效果的

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);
                }
            }
        }

在兩個(gè)地方執(zhí)行:

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);
        }

明顯我們需要對(duì)第二種執(zhí)行情況進(jìn)行修改,使得正在滑動(dòng)的時(shí)候不執(zhí)行貼緊操作,實(shí)現(xiàn)方式就是繼承Behavior類重寫其onStopNestedScroll方法,判斷當(dāng)前是否處于慣性滑動(dòng)操作之中。

3.自定義Behevior源碼如下:
/**
 * @author:honglei92
 * @time:2018/7/26
 */
public class WhlBehavior extends AppBarLayout.Behavior {
    /**
     * 是否處于慣性滑動(dòng)狀態(tài)
     */
    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) {
        //如果不是慣性滑動(dòng),讓他可以執(zhí)行緊貼操作
        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時(shí)處于非慣性滑動(dòng)
        if (type == 1) {
            isFlinging = false;
        }
    }
    @Override
    public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull AppBarLayout child, @NonNull View target, float velocityX, float velocityY, boolean consumed) {
        //慣性滑動(dòng)的時(shí)候設(shè)置為true
        isFlinging = true;
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }
}

附上執(zhí)行效果圖:


執(zhí)行效果圖.gif

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

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

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

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