在Android M Preview
发布后,咱们得到了一个新的support library
—— Android Design Support Library
用来实现Google的Material Design
提供了一系列符合设计标准的控件。html
其中有众多的控件,其中最复杂,功能最强大的就是CoordinatorLayout
,顾名思义,它是用来组织它的子views之间协做的一个父view。CoordinatorLayout默认状况下可理解是一个FrameLayout
,它的布局方式默认是一层一层叠上去。
那么,CoordinatorLayout
的神奇之处就在于Behavior
对象了。
看下CoordinatorLayout.Behavior
对象的 Overviewjava
Interaction behavior plugin for child views of CoordinatorLayout.android
A Behavior implements one or more interactions that a user can take on a child view. These interactions may include drags, swipes, flings, or any other gestures.segmentfault
可知Behavior
对象是用来给CoordinatorLayout的子view们进行交互用的。Behavior
接口拥有不少个方法,咱们拿AppBarLayout
为例。AppBarLayout
中有两个Behavior
,一个是拿来给它本身用的,另外一个是拿来给它的兄弟结点用的,咱们重点关注下AppBarLayout.ScrollingViewBehavior
这个类。布局
咱们看下这个类中的如下方法设计
javapublic boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { return dependency instanceof AppBarLayout; }
这个方法告诉CoordinatorLayout
,这个view是依赖AppBarLayout
的,后续父亲能够利用这个方法,查找到这个child全部依赖的兄弟结点。代理
javapublic boolean onMeasureChild(CoordinatorLayout parent, View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
这个是CoordinatorLayout
在进行measure
的过程当中,利用Behavior
对象对子view进行大小测量的一个方法。
在这个方法内,咱们能够经过parent.getDependencies(child);
这个方法,获取到这个child依赖的view,而后经过获取这个child依赖的view的大小来决定自身的大小。code
javapublic boolean onLayoutChild(CoordinatorLayout parent, View child, int layoutDirection)
这个方法是用来子view用来布局自身使用,若是依赖其余view,那么系统会首先调用htm
javapublic boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency)
这个方法,能够在这个回调中记录dependency
的一些位置信息,在onLayoutChild
中利用保存下来的信息进行计算,而后获得自身的具体位置。对象
javapublic boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
javapublic void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed)
javapublic void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)
javapublic void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target)
这几个方法是否是特别熟悉?我在Android嵌套滑动机制(NestedScrolling) 介绍过,这几个方法恰好是NestedScrollingParent
的方法,也就是对CoodinatorLayout
进行的一个代理(Proxy),即CoordinatorLayout
本身不对这些消息进行处理,而是传递给子view的Behavior
,进行处理。利用这样的方法,实现了view和view之间的交互和视觉的协同(布局、滑动)。
能够看到CoodinatorLayout
给咱们实现了一个能够被子view代理实现方法的一个布局。这和传统的ViewGroup
不一样,子view今后知道了彼此之间的存在,一个子view的变化能够通知到另外一个子view。CoordinatorLayout
所作的事情就是当成一个通讯的桥梁
,链接不一样的view。使用Behavior
对象进行通讯。
咱们具体的实现能够参照 Android官方文档告诉咱们的每个方法的做用 进行重写,实现本身想要的各类复杂的功能。
https://developer.android.com/reference/android/support/design/widget/... 有了这么一套机制,想实现组件之间的交互,就更加方便快捷啦~