前言
CoordinatorLayout 继承于ViewGroup,它就是一个超级强大 Framelayout。CoordinatorLayout 的作用就是协调子 View。
使用场景:
- 作为 一个应用顶层的装饰布局,也就是一个Activity Layout 的最外一层布局。
- As a container for a specific interaction with one or more child views,作为一个或多个有特定响应动作的容器。
解释一下这个动画,蓝色的矩形是我们一个普通 View,黄色的 Hello 是一个 Button。我们水平拖动蓝色矩形时,黄色 Button 查着与蓝色矩形相反方向移动;竖直移动蓝色矩形时,黄色也跟着竖直。
简而言之:它们在竖直方向同步移动,在水平方向相反。
代码实现1. 定义一个类,继承 CoordinatorLayout.Behavior
/**
* 判断child的布局是否依赖dependency
*/
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, T child, View dependency) {
boolean rs;
//根据逻辑判断rs的取值
//返回false表示child不依赖dependency,ture表示依赖
return rs;
}
/**
* 当dependency发生改变时(位置、宽高等),执行这个函数
* 返回true表示child的位置或者是宽高要发生改变,否则就返回false
*/
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, T child, View dependency) {
//child要执行的具体动作
return true;
}
2. 实例代码
public class MyBehavior extends CoordinatorLayout.Behavior {
private int width;
public MyBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics display = context.getResources().getDisplayMetrics();
width = display.widthPixels;
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
//如果dependency是TempView的实例,说明它就是我们所需要的Dependency
return dependency instanceof TempView;
}
//每次dependency位置发生变化,都会执行onDependentViewChanged方法
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, Button btn, View dependency) {
//根据dependency的位置,设置Button的位置
int top = dependency.getTop();
int left = dependency.getLeft();
int x = width - left - btn.getWidth();
int y = top;
setPosition(btn, x, y);
return true;
}
private void setPosition(View v, int x, int y) {
CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) v.getLayoutParams();
layoutParams.leftMargin = x;
layoutParams.topMargin = y;
v.setLayoutParams(layoutParams);
}
}
3. 布局文件