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

Android 自訂 Toast 提示訊息的實作方法

編輯:關於 Android 程式設計

為什麼要自訂

Android 系統預設的 Toast 十分簡潔,使用也非常簡單。但有時候預設樣式與整體介面風格格格不入,這時就需要自訂 Toast,讓它與你的應用更為融合。

步驟一:建立 Toast 的版面檔

自訂 Toast 的第一步是新增一個版面配置檔,其結構與 Activity 使用的版面檔完全一致,差別只在內容是你要呈現在提示訊息裡的元件。以下範例做了一個「圖示 + 文字」的橫向排列:

<?xml version="1.0" encoding="utf-8"?>
<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="10dp"
    android:background="#DAAA" >

    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp" />

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#FFF" />
</LinearLayout>

這裡要特別注意:最外層 LinearLayout 的 id(toast_layout_root)後續程式碼會用到,不能省略。

步驟二:在程式中建立自訂 Toast

public class MainActivity extends Activity {

    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // LayoutInflater 能把 XML 轉成對應的 View 物件
                LayoutInflater inflater = getLayoutInflater();

                // 依指定版面建立具備層級關係的 View,
                // 第二個參數是根節點,即 toast_layout_root 的 id
                View layout = inflater.inflate(R.layout.toast_layout,
                        (ViewGroup) findViewById(R.id.toast_layout_root));

                // 注意:以下兩個 findViewById 都是在 layout 中查找
                ImageView image = (ImageView) layout.findViewById(R.id.image);
                image.setImageResource(R.drawable.head);

                TextView text = (TextView) layout.findViewById(R.id.text);
                text.setText("自定義Toast演示程序");

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); // 設定顯示位置
                toast.setDuration(Toast.LENGTH_LONG);            // 設定顯示時間
                toast.setView(layout);                           // 套用自訂版面
                toast.show();
            }
        });
    }
}

幾個容易寫錯的地方:

  • inflate() 的第二個參數必須是版面檔中的根 View id,這樣回傳的 View 才帶有正確的父層結構。
  • 後續的 findViewById() 一定要在 layout 上呼叫,而不是在 Activity 上呼叫,否則找不到 Toast 內部的元件。
  • setGravity() 的第二、三個參數是 x、y 偏移量,可用來微調位置。
  • 顯示時間只有 Toast.LENGTH_SHORT 與 Toast.LENGTH_LONG 兩種可選,無法自訂任意秒數。

執行結果

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