溫馨提示×

Android怎么自定義Toast樣式

小億
156
2023-08-11 20:33:02
欄目: 編程語言

要自定義Toast樣式,可以按照以下步驟進行操作:

  1. 創建一個自定義的Toast布局文件。在res目錄下的layout文件夾中創建一個toast_layout.xml文件,并自定義Toast的樣式,例如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:orientation="horizontal"
android:padding="8dp">
<ImageView
android:id="@+id/toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_toast" />
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="16sp" />
</LinearLayout>
  1. 在Java代碼中使用自定義的Toast布局文件。在你需要顯示Toast的地方,使用LayoutInflater加載自定義的Toast布局文件,并設置Toast的顯示時長,例如:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout));
TextView text = layout.findViewById(R.id.toast_text);
text.setText("這是自定義的Toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

在上述代碼中,通過LayoutInflater加載toast_layout.xml文件,并找到其中的TextView控件設置顯示的文本內容。然后創建一個Toast實例,并通過setView()方法將自定義的布局文件設置給Toast,最后使用show()方法顯示Toast。

注意:記得將上述代碼中的R.layout.toast_layout替換為你自定義的Toast布局文件的名稱。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女