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

自定義 Toast 提示框(一):用 shape 樣式做出圓角邊框的版面

編輯:關於 Android 開發

為什麼要自定義 Toast

系統預設的 Toast 只有一行灰底白字,功能上沒問題,但放進講究視覺細節的 App 裡總顯得突兀。自定義 Toast 的做法是把版面拆成兩件事:長什麼樣子交給 layout 與 shape 樣式檔,什麼時候出現交給 Java 程式碼。本篇先完成前半段,把樣子做出來。

開發步驟

  • 在 res/layout 下新增 Toast 的版面資源檔 toast_customer.xml。
  • 在這個版面最外層的容器上加上 android:id,後續程式碼要靠它取得根 View。
  • 在 res/drawable 下新增樣式規則檔,定義圓角、底色與描邊。
  • 讓版面檔引用這份樣式。

版面檔 toast_customer.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/toastMessage"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:gravity="center_horizontal|center_vertical"
        android:textSize="13dp"
        android:textColor="#000000" />
</LinearLayout>

樣式檔 toast_border_bg.xml

用 shape 標籤就能畫出圓角矩形,不必準備任何圖片素材,這也是 Android 樣式系統最實用的地方之一。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <corners android:radius="8dp" />
    <solid android:color="#55FFFFFF" />
    <stroke android:width="0.5dp" android:color="#FFFFFF" />
</shape>

三個子標籤分別負責:8dp 的圓角、半透明白色底(透明度 0x55)、以及 0.5dp 的白色描邊。

讓版面引用樣式

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@drawable/toast_border_bg">

    <TextView
        android:id="@+id/toastMessage"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:gravity="center_horizontal|center_vertical"
        android:textSize="22dp"
        android:text="測試"
        android:textColor="#000000" />
</LinearLayout>

執行後即可看到帶圓角與描邊的提示框。

下一步

版面準備好之後,接下來只要在程式碼中透過 LayoutInflater 把這個版面填出來,塞進 Toast 並用 setView() 指定即可。屆時還可以加上自訂的置放位置與顯示時長,讓提示訊息更貼合你的設計稿。

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