1. 程式人生 > >Android基礎:自定義帶圖片的Toast

Android基礎:自定義帶圖片的Toast

由於Android系統的預設Toast比較單調,而且不同手機型號Toast的顯示也大一樣。如下圖所示,有些Toast需要能夠顯示圖片,還要有一堆的透明度,而且顯示位置也有要求,所以,為了滿足專案的需求,我們需要用到自定義的Toast。


一、Toast佈局檔案

自定義Toast首先我們需要給Toast指定一個佈局檔案toast_email.xml,程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <LinearLayout
        android:id="@+id/toast_emailOne_root"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/common_setting_backgroud_shape03"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingBottom="4dp"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"
        android:paddingTop="4dp" >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/prompt_report" />
        <TextView
            android:id="@+id/textToast"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="郵件已經,傳送請注意查收!"
            android:textColor="@color/color14"
            android:textSize="@dimen/text_size4" />
    </LinearLayout>
</LinearLayout>
大概長這個樣子 背景圓角與透明度的程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#77000000" />
    <corners
        android:bottomLeftRadius="20dp"
        android:bottomRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp" />
</shape>

二、自定義Toast工具類

public class ToastEmail {
	public static ToastEmail mToastEmail;
	private Toast toast;

	private ToastEmail() {
	}

	public static ToastEmail getToastEmail() {
		if (mToastEmail == null) {
			mToastEmail = new ToastEmail();
		}
		return mToastEmail;
	}

	/**
	 * 顯示
	 */
	public void ToastShow(Context context, ViewGroup root, String str) {
		View view = LayoutInflater.from(context).inflate(R.layout.toast_email, root);
		TextView text = (TextView) view.findViewById(R.id.textToast);
		text.setText(str); // 設定顯示文字
		toast = new Toast(context);
		toast.setGravity(Gravity.CENTER, 0, 0); // Toast顯示的位置
		toast.setDuration(2000); // Toast顯示的時間
		toast.setView(view);
		toast.show();
	}

	public void ToastCancel() {
		if (toast != null) {
			toast.cancel();
		}
	}
}

三、自定義Toast的使用

使用的時候很簡單,一句程式碼就能夠搞定:
ToastEmail.getToastEmail().ToastShow(context, null, "我是Toast要顯示的文字");
至此,簡單帶圖片的Toast就介紹完了。