CoordinatorLayout自定义Behavior&源码分析

Posted 花花young

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CoordinatorLayout自定义Behavior&源码分析相关的知识,希望对你有一定的参考价值。

前言

        Behavior是android新出的Design库里新增的布局概念。Behavior只有是CoordinatorLayout的直接子View才有意义。可以为任何View添加一个Behavior。Behavior是一系列回调。让你有机会以非侵入的为View添加动态的依赖布局,和处理父布局(CoordinatorLayout)滑动手势的机会。


Part 1、某个View监听另一个View的状态

一个View监听另一个View,只需要在自定义Behavior重写:layoutDependsOn/onDependentViewChanged方法

public class CustomBehavior extends CoordinatorLayout.Behavior<View> 

    public CustomBehavior(Context context, AttributeSet attrs) 
        super(context, attrs);
    

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) 
        //还可以根据ID或者TAG来判断
        return dependency instanceof TextView || super.layoutDependsOn(parent, child, dependency);
    

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) 
        int offSet = dependency.getTop() - child.getTop() - child.getHeight();
        ViewCompat.offsetTopAndBottom(child,offSet);
        return true;
    

tips:

1、自定义Behavior一定要重写构造方法不然就会报错

2、layoutDependsOn(parent,child,dependency) : 用来决定需要监听哪些控件或者容器的状态,parent父容器;child子控件也是观察者;dependency监听的View也是被观察者

3、onDependentViewChanged(parent,child,dependecy) : 当被监听的View发生改变的时候回调,可以在此方法里面做一些相应的联动效果

效果~



Part 2、某个View需要监听CoordinateLayout里面所有控件的滑动状态

某个View需要监听CoordinatorLayout里面所有控件的滑动效果需要重写:onStartNestedScroll/onNestedScroll/onNestedPreScroll方法,注意:能被CoordinatorLayout捕获到的滑动状态的控件只有:recyclerView/NestScrollView/ViewPager

public class ScrollBehavior extends CoordinatorLayout.Behavior<View> 
    public ScrollBehavior(Context context, AttributeSet attrs) 
        super(context, attrs);
    

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) 
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
    

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) 
        ((RecyclerView) child).scrollBy(0,dyConsumed);
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
    
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) 

    
    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, View child, View target, float velocityX, float velocityY, boolean consumed) 
        // 快速滑动的惯性移动(松开手指后还会有滑动效果)
        ((RecyclerView) child).fling(0, (int) velocityY);
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    
tips:

1、当快速滑动的时候会出现错位,原因是惯性引起,所以需要在onNestedFling方法调用RecyclerView的fling方法

效果~


Part 3、Behavior源码分析

在CoordinatorLayout源码parseBehavior函数中,此函数是在初始化CoordinatorLayout.LayoutParams的时候调用

            if (c == null) 
                final Class<Behavior> clazz = (Class<Behavior>) Class.forName(fullName, true,
                        context.getClassLoader());
                c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
                c.setAccessible(true);
                constructors.put(fullName, c);
            
            return c.newInstance(context, attrs);
其中CONSTRUCTOR_PARAMS

    static final Class<?>[] CONSTRUCTOR_PARAMS = new Class<?>[] 
            Context.class,
            AttributeSet.class
    ;
由此可见必须要在子类中重写构造方法

根据Part 1 和Part 2来查看源码,首先Part 1中的layoutDependsOn和onDependentViewChanged是在CoordinatorLayout类onChildViewsChanged方法中进行调用

    final void onChildViewsChanged(@DispatchChangeEvent final int type) 
        ......
        for (int i = 0; i < childCount; i++) 
            final View child = mDependencySortedChildren.get(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            if (type == EVENT_PRE_DRAW && child.getVisibility() == View.GONE) 
                // Do not try to update GONE child views in pre draw updates.
                continue;
            
         ......
            // Update any behavior-dependent views for the change
            for (int j = i + 1; j < childCount; j++) 
                final View checkChild = mDependencySortedChildren.get(j);
                final LayoutParams checkLp = (LayoutParams) checkChild.getLayoutParams();
                final Behavior b = checkLp.getBehavior();

                if (b != null && b.layoutDependsOn(this, checkChild, child)) 
                    if (type == EVENT_PRE_DRAW && checkLp.getChangedAfterNestedScroll()) 
                        // If this is from a pre-draw and we have already been changed
                        // from a nested scroll, skip the dispatch and reset the flag
                        checkLp.resetChangedAfterNestedScroll();
                        continue;
                    
                    final boolean handled;
                    switch (type) 
                        case EVENT_VIEW_REMOVED:
                            // EVENT_VIEW_REMOVED means that we need to dispatch
                            // onDependentViewRemoved() instead
                            b.onDependentViewRemoved(this, checkChild, child);
                            handled = true;
                            break;
                        default:
                            // Otherwise we dispatch onDependentViewChanged()
                            handled = b.onDependentViewChanged(this, checkChild, child);
                            break;
                    

                    if (type == EVENT_NESTED_SCROLL) 
                        // If this is from a nested scroll, set the flag so that we may skip
                        // any resulting onPreDraw dispatch (if needed)
                        checkLp.setChangedAfterNestedScroll(handled);
                    
                
            
        
    
从源码中看出当Child为GONE时将不会执行后面的onDependenViewChanged等方法

通过查看onChildViewsChanged方法的调用的源头可以看出最终也是由onNestedPreScroll和onNestedScroll调用

    @Override
    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
            int dxUnconsumed, int dyUnconsumed) 
        final int childCount = getChildCount();
        boolean accepted = false;
        for (int i = 0; i < childCount; i++) 
            final View view = getChildAt(i);
            if (view.getVisibility() == GONE) //如果为GONE则跳过
                // If the child is GONE, skip...
                continue;
            

            final LayoutParams lp = (LayoutParams) view.getLayoutParams();
            if (!lp.isNestedScrollAccepted()) 
                continue;
            
            final Behavior viewBehavior = lp.getBehavior();
            if (viewBehavior != null) 
                viewBehavior.onNestedScroll(this, view, target, dxConsumed, dyConsumed,
                        dxUnconsumed, dyUnconsumed);
                accepted = true;//当调用了Behavior的onNestedScroll方法也将会调用onChildViewChanged方法
            
        

        if (accepted) 
            onChildViewsChanged(EVENT_NESTED_SCROLL);//调用了上面提到的onChildViewChanged方法进而调用layoutDependsOn和onDependentViewChanged
        
    
当时onStartNestedScroll方法并没有调用,当然这也和在onStartNestedScroll方法进行判断滑动View是竖直还是水平有关

    @Override
    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) 
        boolean handled = false;

        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) 
            final View view = getChildAt(i);
            if (view.getVisibility() == View.GONE) 
                // If it's GONE, don't dispatch
                continue;
            
            final LayoutParams lp = (LayoutParams) view.getLayoutParams();
            final Behavior viewBehavior = lp.getBehavior();
            if (viewBehavior != null) 
                final boolean accepted = viewBehavior.onStartNestedScroll(this, view, child, target,
                        nestedScrollAxes);
                handled |= accepted;

                lp.acceptNestedScroll(accepted);
             else 
                lp.acceptNestedScroll(false);
            
        
        return handled;
    
至此简易的源码介绍结束




以上是关于CoordinatorLayout自定义Behavior&源码分析的主要内容,如果未能解决你的问题,请参考以下文章

CoordinatorLayout+ViewPager+RecyclerView+自定义TabLayout布局

CoordinatorLayout自定义Behavior&源码分析

使用CoordinatorLayout打造各种炫酷的效果

当 SnackBar 出现在 CoordinatorLayout 中时上移视图

自定义类中的 Snackbar 未显示

xamarin.forms 从自定义渲染器访问 viewmodel 属性