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

Android 自定義 Toast:換掉系統默認樣式

編輯:關於 Android 程式設計

系統默認的 Toast 只有一行灰底白字,想放個圖標或換個配色就得自定義。做法並不複雜,照著 API 走兩步就好:先寫一個布局,再用 setView() 塞進 Toast。

效果圖:

第一步:自定義布局 toast.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/toast" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="25sp" />
</LinearLayout>

第二步:封裝成工具類

public class MyToast extends Toast {

    public MyToast(Context context, String msg) {
        super(context);
        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.toast, null);

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText(msg);

        setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        setDuration(LENGTH_SHORT);
        setView(layout);
    }
}

使用時直接 new MyToast(this, "提示內容").show(); 即可。

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