Android官方文檔—User Interface(Toasts)

Toasts

Toast在小彈出窗口中提供有關操作的簡單反饋。它僅填充消息所需的空間量,並且當前活動保持可見和交互。例如,在發送電子郵件之前導航離開電子郵件會觸發“草稿保存”吐司,以便您知道以後可以繼續編輯。超時後,Toasts會自動消失。

如果需要用戶對狀態消息的響應,請考慮使用通知。

基礎


首先,使用makeText()方法之一實例化Toast對象。此方法有三個參數:應用程序上下文,文本消息和Toast的持續時間。它返回一個正確初始化的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對象,如下所示:

Toast.makeText(context, text, duration).show();

定位你的吐司


標準吐司通知出現在屏幕底部附近,水平居中。您可以使用setGravity(int,int,int)方法更改此位置。這接受三個參數:重力常數,x位置偏移和y位置偏移。

例如,如果您確定吐司應該出現在左上角,您可以像這樣設置重力:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

如果要將位置微移到右側,請增加第二個參數的值。要輕推它,請增加最後一個參數的值。

創建自定義Toast視圖


如果簡單的短信不夠,您可以爲Toast通知創建自定義佈局。要創建自定義佈局,請在XML或應用程序代碼中定義View佈局,並將根View對象傳遞給setView(View)方法。

例如,您可以使用以下XML(保存爲layout / custom_toast.xml)爲右側屏幕截圖中顯示的Toast創建佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              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>

請注意,LinearLayout元素的ID是“custom_toast_container”。您必須使用此ID和XML佈局文件“custom_toast”的ID來擴充佈局,如下所示:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                (ViewGroup) findViewById(R.id.custom_toast_container));

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)從XML中擴展布局。第一個參數是佈局資源ID,第二個參數是根視圖。您可以使用此膨脹佈局在佈局中查找更多View對象,因此現在可以捕獲並定義ImageView和TextView元素的內容。最後,使用Toast(Context)創建一個新的Toast並設置Toast的一些屬性,例如重力和持續時間。然後調用setView(View)並將其傳遞給膨脹的佈局。現在,您可以通過調用show()來顯示具有自定義佈局的Toast。

注意:除非要使用setView(View)定義佈局,否則不要將公共構造函數用於Toast。如果您沒有要使用的自定義佈局,則必須使用makeText(Context,int,int)來創建Toast。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章