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

Android 自訂 Toast 提示訊息實作教學

編輯:關於 Android 程式設計

先看 Toast 是怎麼做出來的

翻一下原始碼會發現,Toast.makeText() 的做法其實很直白:透過 Context.LAYOUT_INFLATER_SERVICE 取得一個 LayoutInflater,把系統內建的版面 transient_notification 展開成 View,找出其中的 TextView 塞入文字,最後把這個 View 交給 Toast 物件。

public static Toast makeText(Context context, CharSequence text, int duration) {
    Toast result = new Toast(context);

    LayoutInflater inflate = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
    TextView tv = (TextView) v.findViewById(com.android.internal.R.id.message);
    tv.setText(text);

    result.mNextView = v;
    result.mDuration = duration;

    return result;
}

既然原理是「塞一個自訂 View 進去」,那麼只要換成自己的版面,就能做出帶圖示的 Toast。

第一步:定義版面 res/layout/my_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/iv_my_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/notification" />

    <TextView
        android:id="@+id/tv_my_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="text" />

</LinearLayout>

第二步:封裝成 MyToast 工具類

public class MyToast {

    /**
     * 顯示自定義的 Toast
     * @param context  上下文
     * @param iconid   圖示的資源 id
     * @param text     要顯示的文字
     */
    public static void showToast(Context context, int iconid, String text) {
        View view = View.inflate(context, R.layout.my_toast, null);

        TextView tv = (TextView) view.findViewById(R.id.tv_my_toast);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_my_toast);

        iv.setImageResource(iconid);
        tv.setText(text);

        Toast toast = new Toast(context);
        toast.setDuration(0);
        toast.setView(view);
        toast.show();
    }
}

呼叫方式只需一行:MyToast.showToast(this, R.drawable.notification, "儲存成功");

實務提醒

  • 自訂 Toast 一定要呼叫 setView(),這才是取代系統預設版面的關鍵。
  • setDuration() 只接受 Toast.LENGTH_SHORT(0)與 Toast.LENGTH_LONG(1)兩種值,傳其他數字不會有效果。
  • 較新的 Android 版本對背景執行緒彈出 Toast 有較嚴格的限制,若在非 UI 執行緒呼叫,記得切回主執行緒。
  • Toast 無法取得焦點、也攔不到點擊事件,需要互動時應該改用 Dialog 或 Snackbar。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved