摘自 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