这交互炸了系列:仿小米音乐歌手详情页,自定义 Behavior实战

作者:彭冠铭
链接:https://juejin.im/post/5ede3b0a51882542e723015d

完全是使用嵌套滚动机制实现的,当时就有很多留言说CoordinatorLayout也能实现,确实,这不文章就来了。

作者这个系列一共 4 篇,2 篇基础,2 篇实战,如果你能完全吸收,基本玩转嵌套滚动。

PS:感谢大家,昨天很给力,让我褥了好几年…

1概述

之前的《浅析NestedScrolling嵌套滑动机制之CoordinatorLayout.Behavior》带大家了解CoordinatorLayout.Behavior的原理和基本使用,这篇文章手把手基于自定义Behavior实现小米音乐歌手详情页。

效果预览

效果分析

布局主要有上图四部分组成,逻辑上的层级如图所示有2层。

滑动Content部分时利用View的TransitionY属性改变位置来消耗滑动值,而Face、TopBar、TitleBar部分的Behavior依赖Content,监听Content部分的TransitionY设定各种范围从而计算百分比来执行位移、Alpha效果。

下面来说明上图中变量的意义:

topBarHeight;//topBar高度
contentTransY;//滑动内容初始化TransY
downEndY;//content下滑的最大值
content部分的上滑范围=[topBarHeight,contentTransY]
content部分的下滑范围=[contentTransY,downEndY]

2代码实现

布局

下面是布局要点,侧重于控件的尺寸和位置,完整布局请参考:

<?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、嵌套滑动。

绑定需要做效果的View、引入Dimens、测量Content部分的高度

从上面图片能够分析出:

折叠状态时,Content部分高度=满屏高度-TopBar部分的高度

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的垂直方向的滑动。

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()

接下来就是处理滑动,上面效果分析提过:

Content部分的:

上滑范围=[topBarHeight,contentTransY]、
下滑范围=[contentTransY,downEndY]即滑动范围为[topBarHeight,downEndY];

ElemeNestedScrollLayout要控制Content部分的TransitionY值要在范围内,具体处理如下:

Content部分里可滑动View往上滑动时:

  1. 如果Content部分当前TransitionY+View滑动的dy > topBarHegiht,设置Content部分的TransitionY为Content部分当前TransitionY+View滑动的dy达到移动的效果来消费View的dy。

  2. 如果Content部分当前TransitionY+View滑动的dy = topBarHegiht,同上操作。

  3. 如果Content部分当前TransitionY+View滑动的dy < topBarHegiht,只消费部分dy(即Content部分当前TransitionY到topBarHeight差值),剩余的dy让View滑动消费。

Content部分里可滑动View往下滑动并且View已经不能往下滑动
(比如RecyclerView已经到顶部还往下滑)时:

  1. 如果Content部分当前TransitionY+View滑动的dy >= topBarHeight 并且 Content部分当前TransitionY+View滑动的dy <= downEndY,设置Content部分的TransitionY为Content部分当前TransitionY+View滑动的dy达到移动的效果来消费View的dy

  2. 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: 从折叠状态快速下滑转为初始化状态,这个过程如下图,看起来像是快速下滑停顿的效果。

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的位移、蒙层的透明度变化,这里因为篇幅原因,只讲解关键方法,具体源码见

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

实战系列

话不多说,Android实战系列 集合,都已经系统分类好,由于文章篇幅问题点击链接查看详细文章以及获取学习笔记链接


猜你喜欢

转载自blog.csdn.net/Android725/article/details/107916927