淺析NestedScrolling嵌套滑動機制之實踐篇-自定義Behavior實現小米音樂歌手詳情

嵌套系列導航

本文已在公衆號鴻洋原創發佈。未經許可,不得以任何形式轉載!php

概述

以前的《淺析NestedScrolling嵌套滑動機制之CoordinatorLayout.Behavior》帶你們瞭解CoordinatorLayout.Behavior的原理和基本使用,這篇文章手把手基於自定義Behavior實現小米音樂歌手詳情頁。github地址:github.com/pengguanmin…java

效果預覽

小米音樂歌手詳情頁效果
apk下載地址: github 百度雲通道 密碼:fu5s

效果分析

層級
佈局主要有上圖四部分組成,邏輯上的層級如圖所示有2層。
狀態
滑動Content部分時利用View的TransitionY屬性改變位置來消耗滑動值,而Face、TopBar、TitleBar部分的Behavior依賴Content,監聽Content部分的TransitionY設定各類範圍從而計算百分比來執行位移、Alpha效果。下面來講明上圖中變量的意義:

topBarHeight;//topBar高度
contentTransY;//滑動內容初始化TransY
downEndY;//content下滑的最大值
content部分的上滑範圍=[topBarHeight,contentTransY]
content部分的下滑範圍=[contentTransY,downEndY]
複製代碼

代碼實現

佈局

下面是佈局要點,側重於控件的尺寸和位置,完整佈局請參考:activity_main.xmlandroid

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent">

    <!--face部分-->
    <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="com.pengguanming.mimusicbehavior.behavior.FaceBehavior">

        <ImageView android:id="@+id/iv_face" android:layout_width="match_parent" android:layout_height="500dp" android:scaleType="centerCrop" android:src="@mipmap/jj" android:tag="iv_face" android:translationY="@dimen/face_trans_y" />

        <View android:id="@+id/v_mask" android:layout_width="match_parent" android:layout_height="500dp" />
    </FrameLayout>
    <!--face部分-->

    <!--TopBar部分-->
    <com.pengguanming.mimusicbehavior.widget.TopBarLayout android:id="@+id/cl_top_bar" android:layout_width="match_parent" android:layout_height="@dimen/top_bar_height" app:layout_behavior="com.pengguanming.mimusicbehavior.behavior.TopBarBehavior">

        <ImageView android:id="@+id/iv_back" ... />

        <TextView android:id="@+id/tv_top_bar_name" a... />

        <com.pengguanming.mimusicbehavior.widget.DrawableLeftTextView android:id="@+id/tv_top_bar_coll" .../>
    </com.pengguanming.mimusicbehavior.widget.TopBarLayout>
    <!--TopBar部分-->

    <!--TitleBar部分-->
    <android.support.constraint.ConstraintLayout android:id="@+id/cls_title_bar" android:layout_width="match_parent" android:layout_height="48dp" app:layout_behavior="com.pengguanming.mimusicbehavior.behavior.TitleBarBehavior">

        <TextView .../>

        <com.pengguanming.mimusicbehavior.widget.DrawableLeftTextView .../>
    </android.support.constraint.ConstraintLayout>
    <!--TitleBar部分-->

    <!--Content部分-->
    <LinearLayout android:id="@+id/ll_content" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:translationY="@dimen/content_trans_y" app:layout_behavior="com.pengguanming.mimusicbehavior.behavior.ContentBehavior">

        <com.flyco.tablayout.SlidingTabLayout android:id="@+id/stl" .../>

        <android.support.v4.view.ViewPager android:id="@+id/vp" ... />
    </LinearLayout>
    <!--Content部分-->
</android.support.design.widget.CoordinatorLayout>
複製代碼

ContentBehavior

這個Behavior主要處理Content部分的Measure、嵌套滑動。git

綁定須要作效果的View、引入Dimens、測量Content部分的高度

從上面圖片可以分析出:摺疊狀態時,Content部分高度=滿屏高度-TopBar部分的高度github

public class ContentBehavior extends CoordinatorLayout.Behavior{
    private int topBarHeight;//topBar內容高度
    private float contentTransY;//滑動內容初始化TransY
    private float downEndY;//下滑時終點值
    private View mLlContent;//Content部分

    public ContentBehavior(Context context) {
        this(context, null);
    }

    public ContentBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        //引入尺寸值
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
        contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
        downEndY= (int) context.getResources().getDimension(R.dimen.content_trans_down_end_y);
        ...
    }

    @Override
    public boolean onMeasureChild(@NonNull CoordinatorLayout parent, View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec,int heightUsed) {
        final int childLpHeight = child.getLayoutParams().height;
        if (childLpHeight == ViewGroup.LayoutParams.MATCH_PARENT
                || childLpHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
            //先獲取CoordinatorLayout的測量規格信息,若不指定具體高度則使用CoordinatorLayout的高度
            int availableHeight = View.MeasureSpec.getSize(parentHeightMeasureSpec);
            if (availableHeight == 0) {
                availableHeight = parent.getHeight();
            }
            //設置Content部分高度
            final int height = availableHeight - topBarHeight;
            final int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height,
                    childLpHeight == ViewGroup.LayoutParams.MATCH_PARENT
                            ? View.MeasureSpec.EXACTLY
                            : View.MeasureSpec.AT_MOST);
            //執行指定高度的測量,並返回true表示使用Behavior來代理測量子View
            parent.onMeasureChild(child, parentWidthMeasureSpec,
                    widthUsed, heightMeasureSpec, heightUsed);
            return true;
        }
        return false;
    }

    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
        boolean handleLayout = super.onLayoutChild(parent, child, layoutDirection);
        //綁定Content View
        mLlContent=child;
        return handleLayout;
    }
}
複製代碼

現實NestedScrollingParent2接口

onStartNestedScroll()

ContentBehavior只處理Content部分裏可滑動View的垂直方向的滑動。app

public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        //只接受內容View的垂直滑動
        return directTargetChild.getId() == R.id.ll_content
                &&axes== ViewCompat.SCROLL_AXIS_VERTICAL;
    }
複製代碼

onNestedPreScroll()

接下來就是處理滑動,上面效果分析提過:ide

Content部分的上滑範圍=[topBarHeight,contentTransY]、 下滑範圍=[contentTransY,downEndY]即滑動範圍爲[topBarHeight,downEndY];ElemeNestedScrollLayout要控制Content部分的TransitionY值要在範圍內,具體處理以下。 Content部分裏可滑動View往上滑動時:佈局

  • 一、若是Content部分當前TransitionY+View滑動的dy > topBarHegiht,設置Content部分的TransitionY爲Content部分當前TransitionY+View滑動的dy達到移動的效果來消費View的dy。
  • 二、若是Content部分當前TransitionY+View滑動的dy = topBarHegiht,同上操做。
  • 三、若是Content部分當前TransitionY+View滑動的dy < topBarHegiht,只消費部分dy(即Content部分當前TransitionY到topBarHeight差值),剩餘的dy讓View滑動消費。

Content部分裏可滑動View往下滑動而且View已經不能往下滑動 (好比RecyclerView已經到頂部還往下滑)時:post

  • 一、若是Content部分當前TransitionY+View滑動的dy >= topBarHeight 而且 Content部分當前TransitionY+View滑動的dy <= downEndY,設置Content部分的TransitionY爲Content部分當前TransitionY+View滑動的dy達到移動的效果來消費View的dy。
  • 二、Content部分當前TransitionY+View滑動的dy > downEndY,只消費部分dy(即Content部分當前TransitionY到downEndY差值)並中止NestedScrollingChild2的View滾動。
public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
        float transY = child.getTranslationY() - dy;

        //處理上滑
        if (dy > 0) {
            if (transY >= topBarHeight) {
                translationByConsume(child, transY, consumed, dy);
            } else {
                translationByConsume(child, topBarHeight, consumed, (child.getTranslationY() - topBarHeight));
            }
        }

        if (dy < 0 && !target.canScrollVertically(-1)) {
            //處理下滑
            if (transY >= topBarHeight && transY <= downEndY) {
                translationByConsume(child, transY, consumed, dy);
            } else {
                translationByConsume(child, downEndY, consumed, (downEndY-child.getTranslationY()));
                stopViewScroll(target);
            }
        }
    }

    private void stopViewScroll(View target){
        if (target instanceof RecyclerView) {
            ((RecyclerView) target).stopScroll();
        }
        if (target instanceof NestedScrollView) {
            try {
                Class<? extends NestedScrollView> clazz = ((NestedScrollView) target).getClass();
                Field mScroller = clazz.getDeclaredField("mScroller");
                mScroller.setAccessible(true);
                OverScroller overScroller = (OverScroller) mScroller.get(target);
                overScroller.abortAnimation();
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private void translationByConsume(View view, float translationY, int[] consumed, float consumedDy) {
        consumed[1] = (int) consumedDy;
        view.setTranslationY(translationY);
    }
複製代碼

onStopNestedScroll()

在下滑Content部分從初始狀態轉換到展開狀態的過程當中鬆手就會執行收起的動畫,這邏輯在onStopNestedScroll()實現,但注意若是動畫未執行完畢手指再落下滑動時,應該在onNestedScrollAccepted()取消當前執行中的動畫。 動畫

收起動畫

private static final long ANIM_DURATION_FRACTION = 200L;
    private ValueAnimator restoreAnimator;//收起內容時執行的動畫

    public ContentBehavior(Context context, AttributeSet attrs) {
        ...
        restoreAnimator = new ValueAnimator();
        restoreAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                translation(mLlContent, (float) animation.getAnimatedValue());
            }
        });
    }

    public void onNestedScrollAccepted(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        if (restoreAnimator.isStarted()) {
            restoreAnimator.cancel();
        }
    }

    public void onStopNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int type) {
        //若是是從初始狀態轉換到展開狀態過程觸發收起動畫
        if (child.getTranslationY() > contentTransY) {
            restore();
        }
    }

    private void restore(){
        if (restoreAnimator.isStarted()) {
            restoreAnimator.cancel();
            restoreAnimator.removeAllListeners();
        }
        restoreAnimator.setFloatValues(mLlContent.getTranslationY(), contentTransY);
        restoreAnimator.setDuration(ANIM_DURATION_FRACTION);
        restoreAnimator.start();
    }

    private void translation(View view, float translationY) {
        view.setTranslationY(translationY);
    }
複製代碼

處理慣性滑動

場景1:快速往上滑動Content部分的可滑動View產生慣性滑動,這和前面onNestedPreScroll()處理上滑的效果如出一轍,所以能夠複用邏輯。

場景2:從初始化狀態快速下滑轉爲展開狀態,這也和和前面onNestedPreScroll()處理上滑的效果如出一轍,所以能夠複用邏輯。

場景3:從摺疊狀態快速下滑轉爲初始化狀態,這個過程以下圖,看起來像是快速下滑停頓的效果。

下滑慣性滑動

private boolean flingFromCollaps=false;//fling是否從摺疊狀態發生的

public boolean onNestedPreFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, float velocityX, float velocityY) {
        flingFromCollaps=(child.getTranslationY()<=contentTransY);
        return false;
    }

public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
        float transY = child.getTranslationY() - dy;
        ...
        if (dy < 0 && !target.canScrollVertically(-1)) {
            //下滑時處理Fling,摺疊時下滑Recycler(或NestedScrollView) Fling滾動到contentTransY中止Fling
            if (type == ViewCompat.TYPE_NON_TOUCH&&transY >= contentTransY&&flingFromCollaps) {
                flingFromCollaps=false;
                translationByConsume(child, contentTransY, consumed, dy);
                stopViewScroll(target);
                return;
            }
            ...
        }
    }
複製代碼

釋放資源

在ContentBehavior被移除時候,執行要中止動畫、釋放監聽者的操做。

public void onDetachedFromLayoutParams() {
        if (restoreAnimator.isStarted()) {
            restoreAnimator.cancel();
            restoreAnimator.removeAllUpdateListeners();
            restoreAnimator.removeAllListeners();
            restoreAnimator = null;
        }
        super.onDetachedFromLayoutParams();
    }
複製代碼

FaceBehavior

這個Behavior主要處理Face部分的ImageView的位移、蒙層的透明度變化,這裏由於篇幅緣由,只講解關鍵方法,具體源碼見FaceBehavior.class

public class FaceBehavior extends CoordinatorLayout.Behavior {
    private int topBarHeight;//topBar內容高度
    private float contentTransY;//滑動內容初始化TransY
    private float downEndY;//下滑時終點值
    private float faceTransY;//圖片往上位移值

    public FaceBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        //引入尺寸值
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
        contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
        downEndY= (int) context.getResources().getDimension(R.dimen.content_trans_down_end_y);
        faceTransY= context.getResources().getDimension(R.dimen.face_trans_y);
        ...
    }

    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //依賴Content View
        return dependency.getId() == R.id.ll_content;
    }

    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //計算Content的上滑百分比、下滑百分比
        float upPro = (contentTransY- MathUtils.clamp(dependency.getTranslationY(), topBarHeight, contentTransY)) / (contentTransY - topBarHeight);
        float downPro = (downEndY- MathUtils.clamp(dependency.getTranslationY(), contentTransY, downEndY)) / (downEndY - contentTransY);

        ImageView iamgeview = child.findViewById(R.id.iv_face);
        View maskView =  child.findViewById(R.id.v_mask);

        if (dependency.getTranslationY()>=contentTransY){
            //根據Content上滑百分比位移圖片TransitionY
            iamgeview.setTranslationY(downPro*faceTransY);
        }else {
            //根據Content下滑百分比位移圖片TransitionY
            iamgeview.setTranslationY(faceTransY+4*upPro*faceTransY);
        }
        //根據Content上滑百分比設置圖片和蒙層的透明度
        iamgeview.setAlpha(1-upPro);
        maskView.setAlpha(upPro);
        //由於改變了child的位置,因此返回true
        return true;
    }
}
複製代碼

其實從上面代碼也能夠看出邏輯很是簡單,在layoutDependsOn()依賴Content,在onDependentViewChanged()裏計算Content的上、下滑動百分比來處理圖片和蒙層的位移、透明變化。

TopBarBehavior

這個Behavior主要處理TopBar部分的兩個子View的透明度變化,由於邏輯跟FaceBehavior十分相似就不細說了。

public class TopBarBehavior extends CoordinatorLayout.Behavior {
    private float contentTransY;//滑動內容初始化TransY
    private int topBarHeight;//topBar內容高度
    ...

    public TopBarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        //引入尺寸值
        contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
    }

    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //依賴Content
        return dependency.getId() == R.id.ll_content;
    }

    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //計算Content上滑的百分比,設置子view的透明度
        float upPro = (contentTransY- MathUtils.clamp(dependency.getTranslationY(), topBarHeight, contentTransY)) / (contentTransY - topBarHeight);
        View tvName=child.findViewById(R.id.tv_top_bar_name);
        View tvColl=child.findViewById(R.id.tv_top_bar_coll);
        tvName.setAlpha(upPro);
        tvColl.setAlpha(upPro);
        return true;
    }
}
複製代碼

TitleBarBehavior

這個Behavior主要處理TitleBar部分在佈局位置緊貼Content頂部和關聯的View的透明度變化。

public class TitleBarBehavior extends CoordinatorLayout.Behavior {
    private float contentTransY;//滑動內容初始化TransY
    private int topBarHeight;//topBar內容高度

    public TitleBarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        //引入尺寸值
        contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
    }

    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //依賴content
        return dependency.getId() == R.id.ll_content;
    }

    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        //調整TitleBar佈局位置緊貼Content頂部
        adjustPosition(parent, child, dependency);
        //這裏只計算Content上滑範圍一半的百分比
        float start=(contentTransY +topBarHeight)/2;
        float upPro = (contentTransY-MathUtils.clamp(dependency.getTranslationY(), start, contentTransY)) / (contentTransY - start);
        child.setAlpha(1-upPro);
        return true;
    }

    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
        //找到Content的依賴引用
        List<View> dependencies = parent.getDependencies(child);
        View dependency = null;
        for (View view : dependencies) {
            if (view.getId() == R.id.ll_content) {
                dependency = view;
                break;
            }
        }
        if (dependency != null) {
            //調整TitleBar佈局位置緊貼Content頂部
            adjustPosition(parent, child, dependency);
            return true;
        } else {
            return false;
        }
    }

    private void adjustPosition(@NonNull CoordinatorLayout parent, @NonNull View child, View dependency) {
        final CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        int left = parent.getPaddingLeft() + lp.leftMargin;
        int top = (int) (dependency.getY() - child.getMeasuredHeight() + lp.topMargin);
        int right = child.getMeasuredWidth() + left - parent.getPaddingRight() - lp.rightMargin;
        int bottom = (int) (dependency.getY() - lp.bottomMargin);
        child.layout(left, top, right, bottom);
    }
}
複製代碼

總結

自定義Behavior能夠實現各類神奇的效果,相對於自定義View實現NestedScrolling機制,Behavior更能解耦邏輯,但同時又多了些約束,因爲本人水平有限僅給各位提供參考,但願可以拋磚引玉,若是有什麼能夠討論的問題能夠在評論區留言或聯繫本人。

相關文章
相關標籤/搜索