摘自 google material design 文档html
Android 另外提供了一个 Toast,主要用于系统消息。Toasts 跟 SnacKers 相似,可是不能包含 actions 和 不能懂屏幕滑动关闭掉。android
用 make() 方法建立一个 Toast
实例,而后调用 show() 方法。google
Toast.makeText(context, "No network connection.", duration).show();
使用 makeText()
方法的 duration
参数 或者 setDuration
方法指定 Snackbar 在屏幕上显示多长时间。spa
// 你只能使用这两个预约义的常量 duration = Toast.LENGTH_SHORT; // 2000 秒 duration = Toast.LENGTH_LONG; // 3500 秒 toast.setDuration(duration);
能够在任什么时候候使用 cancel()
方法手动的去隐藏 Toast
。翻译
Toast toast= Toast.make(view, text, duration).show(); toast.cancel(); //隐藏吐司
若是在它显示的时候关闭它或者在不想显示的时候它仍然显示,一般你不须要去调用这个方法。它会在持续适当的时间以后本身消失。code
用 setGravity()
能够改变 Toast
的显示位置。component
int gravity = Gravity.CENTER; // Toast在屏幕中的位置,当前属性设置在屏幕中间 int xOffset = 0; // 水平偏移距离 int yOffset = 0; // 垂直偏移距离 Toast toast= Toast.make(view, text, duration); toast.setGravity(gravity, xOffset, yOffset);
// 建立 Toast 实例 Toast toast = Toast.makeText(context, text, duration); // 设置消息颜色 TextView textView= (TextView) toast.getView().findViewById(android.R.id.message); textView.setTextColor(Color.YELLOW); // 设置背景颜色 toast.getView().setBackgroundColor(getResources().getColor(R.color.indigo));
I. 在 layout.xml
文件内的任意位置声明你的自定义 View。xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/txtMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableStart="@drawable/ic_report_problem" android:drawablePadding="8dp" android:paddingTop="8dp" android:paddingBottom="8dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:gravity="center" android:textColor="@android:color/white" android:textSize="16dp" android:text="No connection." android:background="@color/indigo"/>
II. 经过 setView()
方法设置你的自定义 View 到 Toast
。htm
// 建立 Toast 实例 Toast toast = new Toast(getApplicationContext()); // 建立自定义 view View view = getLayoutInflater().inflate(R.layout.toast_view, null); // 设置自定义 view toast.setView(view); // 设置显示持续时间 toast.setDuration(Toast.LENGTH_LONG); // 设置位置 int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin); toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin); // 显示 Toast toast.show();
翻译水平有限,欢迎指正。utf-8