Toast客製化介面

直接 new 出來的Toast是無介面的。

所以直接使用setText(),會拋出例外而讓程式陣亡。

如下:

Toast toast = new Toast(context);
//設定持續時間
toast.setDuration(duration);
toast.setText(text); // java.lang.RuntimeException !!
//使用show()把Toast顯示出來
toast.show();

所以我們可以自己 new 一個Textview,然後使用setView(View)方法把View的根元件透過參數傳遞進去。

TextView textView = new TextView(context);
textView.setText(text);

Toast toast = new Toast(context);
//設定持續時間
toast.setDuration(duration);
//設定顯示的view
toast.setView(textView);
//使用show()把Toast顯示出來
toast.show();

以下介紹幾種客製化界面

基本預設

Toast.makeText( context , "基本預設" , duration).show();

自訂顯示位置在正中央

Toast toast = Toast.makeText( context , text , duration);
//設定顯示位置
toast.setGravity(Gravity.CENTER, 0, 0);
//使用show()把Toast顯示出來
toast.show();

以圖片顯示的

ImageView imageView = new ImageView(context);
imageView.setBackgroundResource(R.drawable.ic_launcher);

Toast toast = new Toast(context);
//設定持續時間
toast.setDuration(duration);
//設定顯示的view
toast.setView(imageView);
//使用show()把Toast顯示出來
toast.show();

全部都以客製化方式呈現的

如範例建立了一個LinearLayout版面,透過Toast顯示一張圖片,檔案儲存為custom_toast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#d0007700"
android:orientation="vertical"
android:padding="8dp">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="8dp"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:textSize="26sp" />
</LinearLayout>

View的根元件LinearLayout元素使用的ID名稱為『toast_layout_root』。你也必須在程式碼當中使用這個ID來inflate你的的XML版面。

如下程式碼:

//inflater可以把xml的資源轉成view
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(this);
//設定顯示位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
//設定持續時間
toast.setDuration(Toast.LENGTH_LONG);
//設定顯示的view
toast.setView(layout);
//使用show()把Toast顯示出來
toast.show();