Toast通知是在視窗表面彈出的一個簡短的小訊息。它只填充訊息所需要的空間,並且使用者當前的Activity依然保持可見度和互動性。這種通知可自動的淡入淡出,且不接受使用者的互動事件。Toast通知能夠被Activity或Service建立並顯示。如果你建立了一個源自Service的Toast通知,它會顯示在當前的Activity最上層。
下面介紹一個Toast裡面的常用方法:
1.makeText()方法
public static Toast makeText (Context context, CharSequence text, int duration)public static Toast makeText (Context context, int resId, int duration)
可以使用makeText()方法擷取一個Toast執行個體,第一個makeText方法有3個參數:1.應用程式的上下文Context、2.要顯示的簡訊;3.Toast通知持續顯示的時間,用show()方法顯示Toast通知。顯示文本也可以使用資源檔裡面的字串。
Context context = getApplicationContext();CharSequence text = "Hello toast!";int duration = Toast.LENGTH_SHORT;Toast toast = Toast.makeText(context, text, duration);toast.show();
當然可以直接使用組合方法且避免建立Toast對象:
Toast.makeText(context, text, duration).show();
2.setGravity()
這個方法很簡單,設定Toast的顯示位置:
toast.setGravity(Gravity.CENTER, 0, 0);//設定Toast顯示位置置中
3.setView()
通過查看Toast原始碼,我們發現該類裡麵包含有一個View變數mNextView,所以可以使用setView()來實現我們自訂Toast的需求。這個方法可以讓我們使用自訂的Toast,如下例子所示:
//自訂toast_layout.xml布局檔案<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="8dp" android:background="#DAAA" > <ImageView android:src="@drawable/droid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFF" /></LinearLayout>//在Activity裡面LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.toast_layout_root));TextView text = (TextView) layout.findViewById(R.id.text);text.setText("This is a custom toast");Toast toast = new Toast(getApplicationContext());toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);toast.setDuration(Toast.LENGTH_LONG);toast.setView(layout);toast.show();
Note:除非你要用setView(View)方法定義布局(layout),否則不要使用公用的Toast類構造器。如果不使用自訂的布局(layout),必須使用makeText(Context, int, int)方法來建立Toast
執行個體示範的話,可以看這個,裡面寫了5種不同的Toast,還提供了下載:
http://www.cnblogs.com/salam/archive/2010/11/10/1873654.html#2390550
還有一點需要注意:
在使用Toast作為提示資訊時,Toast會顯示在螢幕下方,一般用來提示使用者的誤操作。當使用者在某些情況下,使用者連續誤操作多次時,會導致出現很多個Toast,依次顯示,會在頁面上停留很長時間,這個會嚴重影響軟體的使用者親和性。我們可以通過一下方法來實現在一個Toast沒有結束的時候再顯示Toast不累加時間,而是打斷當前的Toast,顯示新的Toast。這樣Toast就不會停留在介面很久。而最多顯示一個Toast提示時間的。
private Toast toast = null; private void showTextToast(String msg) { if (toast == null) { toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT); } else { toast.setText(msg); } toast.show(); }