Step1 简单介绍 CoordinatorLayout
- 作用:协调子 View
- 使用核心: Behavior
- 布局属性类似 FrameLayout
Behavior
两个概念:
Child:CoordinatorLayout 的子 View
Dependency:Child 依赖的 View
简单使用:
定义 Behavior
class SimpleBehavior(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<Button>(context, attrs) {
private val screenWidth: Int = context.resources?.displayMetrics?.widthPixels!!
override fun layoutDependsOn(parent: CoordinatorLayout, child: Button, dependency: View): Boolean {
//判断是否依赖的View
return dependency is WithFingerTextView
}
// 当依赖的 View 位置 宽高发生变化时,执行这个方法
override fun onDependentViewChanged(parent: CoordinatorLayout, child: Button, dependency: View): Boolean {
val x = screenWidth - dependency.x - child.width
// 更新 Child
setPosition(child, x.toInt(), dependency.y.toInt())
return true
}
private fun setPosition(v: View, x: Int, y: Int) {
val layoutParams: CoordinatorLayout.LayoutParams = v.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.leftMargin = x
layoutParams.topMargin = y
v.layoutParams = layoutParams
}
}
布局中使用
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="A Button"
app:layout_behavior="com.jy.friendcircleappbar.SimpleBehavior" /></