Snackbar类似于之前Toast但是它是从底部向上显示,并可以添加点击事件而且配合CoordinatorLayout可以向右滑动删除。
一般使用效果
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.myapplication.MainActivity">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:clickable="true"
android:tint="@android:color/darker_gray"
app:backgroundTint="@color/colorAccent"
app:fabSize="normal"
app:rippleColor="@android:color/darker_gray"
app:srcCompat="@android:drawable/btn_radio" />
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
JAVA
mFAB = (FloatingActionButton) findViewById(R.id.fab);
mFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(mFAB,"测试Snackbar", Snackbar.LENGTH_SHORT).show();
}
});
带点击事件的Snackbar
Snackbar.make(mFAB,"测试Snackbar", Snackbar.LENGTH_SHORT).setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("TAG", "Action响应");
}
}).show();
改变Snackbar背景色
Snackbar sb = Snackbar.make(mFAB,"测试Snackbar", Snackbar.LENGTH_LONG).setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("TAG", "OK");
}
});
View view = sb.getView();
view.setBackgroundColor(Color.RED);
sb.show();