在Android開發中,Toast是一種簡單的彈出提示,用于向用戶顯示臨時的消息。下面是五種情形的Toast使用示例:
Toast.makeText(getApplicationContext(), "普通Toast", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(getApplicationContext(), "帶有圖標的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.ic_icon);
toastLayout.addView(imageView, 0);
toast.show();
首先,創建一個自定義的布局文件toast_custom.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
android:orientation="horizontal"
android:padding="20dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:text="自定義布局的Toast" />
</LinearLayout>
然后,在代碼中使用自定義布局的Toast:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom,
(ViewGroup) findViewById(R.id.toast_custom_layout));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
Toast.makeText(getApplicationContext(), "長時間顯示的Toast", Toast.LENGTH_LONG).show();
Toast toast = Toast.makeText(getApplicationContext(), "位置偏移的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 100, 100);
toast.show();
除了以上的五種情形,你還可以根據自己的需求進行更多的擴展和定制,例如改變Toast的字體樣式、背景顏色等。通過自定義Toast,你可以根據自己的喜好和應用的風格創建屬于自己的Toast。