Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 官方 Toast 使用說明翻譯與實作解析

編輯:關於 Android 程式設計

以下整理自 Android 官方對 Toast 的使用說明。Toast 是一種極為輕量的提示機制,只佔用訊息所需的最小空間,會顯示在目前的 Activity 之上,並在一段時間後自動消失。舉例來說,當你尚未寄出正在撰寫的郵件便離開時,會彈出一個「草稿已保存」的 Toast,提醒你可以稍後繼續編輯。

建立並顯示 Toast

首先透過 Toast.makeText() 建立物件,這個方法有三個參數: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.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);

若想往右移,就加大第二個參數;想往下移,則加大第三個參數。

自定義版面配置

如果單純的文字訊息無法滿足需求,還可以自訂版面。先定義一個檢視(可用 XML 或程式碼),再呼叫 setView(View) 套用。以下是一個包含圖片與文字的自訂版面:

<LinearLayout xmlns:android="https://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) 填充版面(第一個參數是版面 ID,第二個是根檢視)。填充後即可取得內部的 ImageView、TextView 等元素並設定內容。最後透過 Toast(Context) 建立物件,設定位置與顯示時間,呼叫 setView(View),再用 show() 呈現自訂樣式。

最後提醒:除非你需要自訂檢視,否則不要使用公開的建構子。一般情況建議直接用 makeText(Context, int, int) 來建立 Toast 即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved