1、作用
CoordinatorLayout的作用最主要的还是让子View之间能够进行互相通信(例如一个View移动或改变宽高之后,另一个View也跟着改变)。让它们实现通信的东西就是Behavior。
2、使用
1、定义一个类继承CoordinatorLayout.Behavior,重写layoutDependsOn方法和onDependentViewChanged方法,这两个方法的作用见代码:
public class MyBehavior extends CoordinatorLayout.Behavior<View> {
private final int width;
//一定要写这个构造函数,不然会报错
public MyBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
width = displayMetrics.widthPixels;
}
//判断child是否依赖dependency
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof BehaviorView;
}
//当dependency发生改变时(宽高、位置)会触发,返回true表示child也会发生改变
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
//获取dependency改变位置以后的值
int top = dependency.getTop();
int left = dependency.getLeft();
int x = width - left - child.getWidth();
int y = top;
//根据dependency改变的值来改变child的值
// ((View)child.getParent()).scrollTo(x + 100,y);
CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) child.getLayoutParams();
layoutParams.leftMargin = x + 200;
layoutParams.topMargin = y + 100;
child.setLayoutParams(layoutParams);
return true;
}
}
释义:1、CoordinatorLayout.Behavior<View>中的泛型可以使任意类型,只要是你需要产生交互的都可以,不是View的子类也可以;
2、child就是会根据dependency的改变来发生改变的类型,也就是释义1中的泛型;
2、在XML布局中写子View,其中MyBehavior是我自定义的一个View,作用是随着我的手指移动而移动:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#FF0"
android:layout_marginTop="200dp"
android:layout_marginLeft="200dp"
app:layout_behavior="com.zw.myfirstapp.MyBehavior"
/>
<com.zw.myfirstapp.BehaviorView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="200dp"
android:layout_marginTop="200dp"
android:background="#F0F"/>
</android.support.design.widget.CoordinatorLayout>
如上,BehaviorView就是Behavior中的dependency,上面的View就是child,别忘了给child加上layout_behavior属性,也就是我们自定义的一个MyBehavior。