Android系統預設的Toast十分簡潔,使用也非常的簡單。但是有時我們的程式使用預設的Toast時會和程式的整體風格不搭配,這個時候我們就需要自訂Toast,使其與我們的程式更加融合。
使用自訂Toast,首先我們需要添加一個布局檔案,該布局檔案的結構和Activity使用的布局檔案結構一致,在該布局檔案中我們需設計我們Toast的布局,例如:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>
在這個地方要注意,我們給LinearLayout添加的id屬性,在後面的代碼中我們需要使用到。在程式中,我們可以通過如下代碼建立我們自己的Toast:
public class MainActivity extends Activity { private Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //擷取LayoutInflater對象,該對象能把XML檔案轉換為與之一直的View對象 LayoutInflater inflater = getLayoutInflater(); //根據指定的布局檔案建立一個具有層級關係的View對象 //第二個參數為View對象的根節點,即LinearLayout的ID View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); //尋找ImageView控制項 //注意是在layout中尋找 ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.head); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("自訂Toast示範程式"); Toast toast = new Toast(getApplicationContext()); //設定Toast的位置 toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); //讓Toast顯示為我們自訂的樣子 toast.setView(layout); toast.show(); } }); } }
運行效果: