序言
本文力求用最短的篇幅,让读者明白CoordinatorLayout的用法。原理不作深入讨论。
CoordinatorLayout是什么
由Google加入Android系统的一个新的布局容器。相当于一个高级的FrameLayout。它通过Behavior的方式,使容器类的视图能够相互关联,协作,从而轻松地完成一些交互与动效。
CoordinatorLayout 如何接入
compile 'com.android.support:design:23.2.1'
根据自己的complie版本,修改到对应的版本即可。
CoordinatorLayout 如何使用
网上有很多文章结合xxxView,结合yyyView使用,仿佛<b>CoordinatorLayout</b>只能与部分结合使用,其实并非如此!那些奇奇怪怪的View,只是Android官方为我们写好的示例。
<b>CoordinatorLayout</b>的核心是协调,它能够协调任何View之间的动作和效果。它以Behavior类作为连接view的桥梁。
实例演示
需求:界面中有一个Button背景是绿色。点击它弹出一个Snackbar。当Snackbar完全弹出时,Button背景变为红色。当Snackbar准备离开时,Button背景再度变为绿色。
MyButtonBehavior
public class MyButtonBehavior extends CoordinatorLayout.Behavior<Button> {
// 注意:如果没有这个构造方法,xml导入时将报错。
public MyButtonBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
return dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, Button child, View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
float y = ViewCompat.getTranslationY(dependency);
if (y <= 5) {
child.setBackgroundColor(0x44ff0000);
} else {
child.setBackgroundColor(0x4400ff00);
}
}
return false;
}
}
在这个例子中,我们最少需要MyButtonBehavior有三个方法。
- parent 是 Button和Snackbar的容器
- child 是Button
- dependency 是Snackbar
因为在本例中,是Button的背景色依赖Snackbar的位置变化。
布局文件
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#4400ff00"
app:layout_behavior=".MyButtonBehavior"/>
</android.support.design.widget.CoordinatorLayout>
Activity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Hello world", Snackbar.LENGTH_LONG)
.setAction("cancel", new View.OnClickListener() {
@Override
public void onClick(View v) {
}
})
.show();
}
});
}
}
以上就完成了需求中的效果。通过CoordinatorLayout和Behavior,将过去复杂的页面回调封装了起来,使代码更加简洁,开发效率也提高很多。
以上。
网友评论