浅析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更能解耦逻辑,但同时又多了些约束,因为本人水平有限仅给各位提供参考,但愿可以抛砖引玉,若是有什么能够讨论的问题能够在评论区留言或联系本人。

相关文章
相关标签/搜索