以下來自android官方Toast使用說明的譯文
toast是一種簡單到彈出反饋操作。它只佔用了消息所需要的空間大小,並在當前activity顯示和互動。例如,當你退出正在編寫email之前,會提示一個“草稿已保存”的toast來告知你可以稍後繼續編輯。Toast會在一段時間後自動消失。
首先,通過Toast中的makeText()方法創建一個Toast對象。這個方法有三個參數:Context,消息文字,顯示的時間長短。然後,通過show()讓其顯示出來:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
標準的toast會出現在屏幕底部水平中間的位置上,你也可以調用setGravity(int,int,int)改變其顯示的位置。這裏的三個參數,分別表示:Gravity,x方向偏移,y方向偏移。
例如:如果你定義toast顯示在左上角,那麼,你可以這樣寫:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
如果你想讓其位置往右一些,你可以增加第二個參數的值,同理,向下調時,增加最後一個參數的值。
如果這樣一個簡單的消息不能讓你滿意,你還可以創建一個自己定義的佈局。需要定義一個視圖,可以是xml,也可以是代碼的,然後調用setView(View)設置佈局。
例如:
<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>
代碼:
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();
首先,調用getLayoutInflater()(或者getSystemService())方法取出LayoutInflater,然後使用inflate(int,ViewGroup)填充佈局:第一個佈局是layout的ID,第二個是根視圖。你可以使用填充佈局得到更多的內部視圖,得到例如ImageView和TextView元素。最後,通過Toast(Context)創建一個對象,再設置顯示位置、顯示時間長短,然後調用setView(View)。現在,你可以調用show()讓自定義的佈局樣式顯示出來。
注意:不要使用公開的構造方法,除非你需要自定義視圖。如果不使用特別佈局的話,你應該使用makeText(Context,int,int)來創建Toast。