Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

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

編輯:Android 開發實例

系統自帶的 Toast 樣式比較單調,當設計稿要求自定義背景色、邊框甚至圓角時,就必須自己動手。實現思路分兩步:先用 Shape 定義背景,再用自定義布局把文字裝進去。

第一步:定義 Shape 背景

Toast 的背景形狀是圓角的,所以不能直接用一張普通圖片,而要用 <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> 的 radius 則決定圓角幅度。

第二步:編寫自定義布局

新建 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>

第三步:在代碼中加載

關鍵在於不要使用 Toast.makeText(),而是自行構造 Toast 對象並調用 setView() 塞入我們的布局:

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 的 setGravity() 可以調整顯示位置,而 setDuration() 只能取 Toast.LENGTH_SHORT 或 Toast.LENGTH_LONG 兩個值,無法自定義任意時長——這是 framework 層寫死的限制,需要更靈活的提示效果時,通常得改用自定義的浮動窗口。

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