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

Android 自定義邊框與背景顏色的 Toast 提示框

編輯:關於 Android 開發

在 Android 程式設計中,我們偶爾需要自定義 Toast 提示資訊的背景顏色與邊框顏色,以搭配整體介面風格。然而系統默認的 Toast 無法實現這種效果,因此我們需要自定義布局文件;又因為 Toast 的背景是圓角的,所以還需要另外自定義一個 Shape 文件。

步驟一:建立 Shape 邊框文件

先在 drawable-hdpi 目錄下建立一個 my_border.xml 文件,定義背景色、邊框、內距與圓角:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#ff0000ff"/>
    <stroke android:width="1dp" android:color="#FFFFFFFF" />
    <padding android:left="7dp" android:top="7dp"
        android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>

其中 <solid> 設定填充色、<stroke> 設定邊框、<padding> 設定內距、<corners> 設定圓角半徑。

步驟二:建立自定義布局文件

接著建立一個 my_toast.xml 布局文件,並將它的背景設為上一步建立的 Shape 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_border">
    <TextView
        android:layout_width="wrap_content"
        android:id="@+id/TextViewInfo"
        android:layout_height="wrap_content"
        android:text="這是一個自定義背景顏色的提示框"
        android:layout_gravity="center_vertical"
        android:textColor="#ff00ff00">
    </TextView>
</LinearLayout>

步驟三:Java 調用程式碼

最後透過 Java 加載自定義布局,並設定文字內容後顯示:

View toastRoot = getLayoutInflater().inflate(R.layout.my_toast, null);
Toast toast = new Toast(getApplicationContext());
toast.setView(toastRoot);
TextView tv = (TextView) toastRoot.findViewById(R.id.TextViewInfo);
tv.setText("說明:這是一個自定義邊框和底色的提示框。");
toast.show();

透過這三個步驟,就能打造一個擁有自定義邊框與背景顏色的 Toast 提示框,讓提示資訊更貼合你的應用整體視覺風格。

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