一、Toast Notifications
以背景改變方式,提示一些簡短的訊息,訊息視窗自動淡入淡出,不接受互動事件。
例如:當下載某個檔案完成時,可以提示簡短的“儲存成功”。
顯示效果:
建立彈出提示方法:
1、建立Toast對象,可以通過Toast提供的靜態方法makeText(Context context, String message, int duration)
context:應用內容物件,這裡可以傳遞getApplicationContext()
message:提示文本
duration:顯示時間長度,可以使用Toast.LENGTH_SHORT、Toast.LENGTH_LONG
- Context context = getApplicationContext();
-
- Toast toast = Toast.makeText(context, "儲存成功", Toast.LENGTH_LONG);
2、顯示提示,調用show()方法
- toast.show();
上述兩步也可簡寫為:
- Toast.makeText(getApplicationContext(), "儲存成功", Toast.LENGTH_LONG).show();
這樣,最簡單的提示資訊已經完成。現在來看看如何建立自訂外觀Toast notification。
3、自訂外觀Toast通知
3.1、定義XML資源檢視作為提示的外觀
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/toast_layout_root"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:background="#DAAA"
- >
- <ImageView android:id="@+id/image"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp"
- android:src="@drawable/icon"
- />
- <TextView android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#FFF"
- />
- </LinearLayout>
其中TextView文本組件用來顯示需要提示的文本。這裡預設沒有設定文字。
3.2、解析上述XML資源檢視,並設定提示文本
- LayoutInflater inflater = getLayoutInflater();//XML資源布局填充對象
- View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
-
- //修改自訂布局中TextView文本,作為提示資訊
- TextView textView = (TextView) layout.findViewById(R.id.text);
- textView.setText("自訂介面:儲存成功");
3.3、建立Toast對象,並設定視圖、顯示視圖
- Toast toast = new Toast(getApplicationContext());
- //設定垂直置中,水平、垂直位移值為0,表示正中間。
- toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);//設定提示框位置,三個參數分別代表:對其方式、水平位移值、垂直位移值。
- toast.setDuration(Toast.LENGTH_LONG);
- toast.setView(layout);//設定顯示的視圖
- toast.show();
顯示: