CoordinatorLayout是一个加强版的FrameLayout,可以监听其所有子控件的各种事件,然后自动做出最为合理的响应;
如 上一个博文 中提到的Snackbar挡住了悬浮按钮,让CoordinatorLayout监听到Snackbar的弹出事件,自动将内部的FloatingActionButton向上偏移,从而不会遮挡。
添加依赖:
implementation 'com.google.android.material:material:1.3.0'
xml:
由于CoordinatorLayout本身就是一个加强版的FrameLayout,因此下方的操作,不会有副作用。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/test_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/play"
app:backgroundTint="#3F51B5"
app:elevation="3dp"
app:pressedTranslationZ="6dp"
app:rippleColor="@color/colorPrimaryDark"
android:layout_gravity="bottom"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</LinearLayout>
处理监听:
FloatingActionButton test_fab = findViewById(R.id.test_fab);
test_fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "确定这么干吗?", Snackbar.LENGTH_LONG).setAction("yes!", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "操作成功!", Toast.LENGTH_SHORT).show();
}
}).show();
}
});