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

自定義 Toast 的寬高與背景圖片設定

編輯:關於 Android 程式設計

系統預設的 Toast 樣式有限,若需要自訂尺寸、背景與多行內容,可以透過自訂 View 來達成。

Java 端:載入自訂布局

RelativeLayout layout = (RelativeLayout) getLayoutInflater()
        .inflate(R.layout.layout_custom_toast, null);

((TextView) layout.findViewById(R.id.tvCheckoutWay)).setText("11111");
((TextView) layout.findViewById(R.id.tvPercent)).setText("22222");

Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.BOTTOM, 0,
        (int) getResources().getDimension(R.dimen.spacing_4));
toast.setView(layout);   // 指定自訂檢視
toast.show();

布局檔:layout_custom_toast.xml

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

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="48dp"
        android:background="@drawable/bg_toast_data"
        android:gravity="center">

        <TextView
            android:id="@+id/tvCheckoutWay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="AAAA" />

        <TextView
            android:id="@+id/tvPercent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="{100%}"
            android:textColor="@color/green_deep"
            android:textSize="@dimen/text_size_menu" />
    </LinearLayout>
</RelativeLayout>

最容易踩到的地雷

最外層的 Layout 不要放背景圖片,否則寬高怎麼調都不會生效。尺寸與背景都應該設在中間那一層 LinearLayout 上,最外層只當容器用。

補充提醒

從 Android 11(API 30)起,系統對自訂 Toast 檢視做了限制,背景應用無法再顯示自訂樣式的 Toast,只會呈現文字型提示。若需要完全自訂的浮動提示,建議改用 Snackbar 或自行以 WindowManager 實作彈出層。

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