Snackbar
是用来取代Toast的,官方推荐和CoordinatorLayout一起使用在,这样可以让用户右滑退出Snackbar
代码示例
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout android:id="@+id/container" 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" android:fitsSystemWindows="true" tools:context="com.example.myapplication.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main"/> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout>conten_main中的布局是一个Button
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main" tools:context="com.example.myapplication.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn"/> </RelativeLayout>在代码中
//找到CoordinatorLayout控件 final CoordinatorLayout container = (CoordinatorLayout) findViewById(R.id.container); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //setActiion可以设置一个点击按钮实现功能 Snackbar.make(container,"显示的内容",Snackbar.LENGTH_LONG).setAction("点击", new View.OnClickListener() { @Override public void onClick(View v) { Snackbar.make(container,"点击后显示的内容",Snackbar.LENGTH_LONG).show(); } })//设置Action的字体颜色 .setActionTextColor(R.color.material_deep_teal_500) .show(); } });