前言
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<Button> {
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. 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.BFragment">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="300dp"
android:layout_marginTop="300dp"
android:background="#FFCC00"
android:text="Hello"
app:layout_behavior="com.hkt.rxjavatest.ui.MyBehavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>