あなた自身のトーストを生成するAndroidトースト大全(5つのシチュエーション)
Android開発のToastは、ユーザーに一時的なメッセージを表示するために使用される簡単なポップアップです。以下は、5つのシーンでの使用方法例です。
- トースト
Toast.makeText(getApplicationContext(), "普通Toast", Toast.LENGTH_SHORT).show();
- アイコン付きToast
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 = Toast.makeText(getApplicationContext(), "位置偏移的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 100, 100);
toast.show();
それ以外の5つ以上の状況では、トーストのフォントスタイル、背景色を自分流にカスタマイズするなど、さらに多くの拡張やカスタマイズができます。トーストをカスタマイズすることで、自分の嗜好やアプリのスタイルに合わせた独自のトーストを作成できます。