溫馨提示×

toast.maketext如何實現多行顯示

小樊
261
2024-06-28 18:18:28
欄目: 編程語言

在Android中,使用Toast.makeText()方法可以創建一個簡單的Toast消息,但默認情況下Toast消息只會顯示一行文本。如果想要實現多行顯示,可以通過自定義布局來實現。

以下是實現多行顯示的步驟:

  1. 創建一個XML布局文件,例如toast_layout.xml,用來定義Toast消息的布局。在布局文件中可以添加多個TextView來顯示多行文本。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="@android:color/black">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="16sp"/>

</LinearLayout>
  1. 在代碼中使用LayoutInflater加載自定義的布局文件,并設置文本內容。然后通過Toast.setView()方法設置自定義布局,最后顯示Toast消息。
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
        (ViewGroup) findViewById(R.id.toast_layout_root));

TextView textView1 = layout.findViewById(R.id.textView1);
textView1.setText("First line of text");

TextView textView2 = layout.findViewById(R.id.textView2);
textView2.setText("Second line of text");

Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

通過以上步驟,就可以實現多行顯示的Toast消息。需要注意的是,自定義布局的設計和樣式可以根據需求進行修改。

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