toast.maketext如何實(shí)現(xiàn)多行顯示

小樊
125
2024-06-28 18:18:28

在Android中,使用Toast.makeText()方法可以創(chuàng)建一個(gè)簡(jiǎn)單的Toast消息,但默認(rèn)情況下Toast消息只會(huì)顯示一行文本。如果想要實(shí)現(xiàn)多行顯示,可以通過(guò)自定義布局來(lái)實(shí)現(xiàn)。

以下是實(shí)現(xiàn)多行顯示的步驟:

  1. 創(chuàng)建一個(gè)XML布局文件,例如toast_layout.xml,用來(lái)定義Toast消息的布局。在布局文件中可以添加多個(gè)TextView來(lái)顯示多行文本。
<?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加載自定義的布局文件,并設(shè)置文本內(nèi)容。然后通過(guò)Toast.setView()方法設(shè)置自定義布局,最后顯示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();

通過(guò)以上步驟,就可以實(shí)現(xiàn)多行顯示的Toast消息。需要注意的是,自定義布局的設(shè)計(jì)和樣式可以根據(jù)需求進(jìn)行修改。

0