Android 中的多行文本如何

How do multiline text in Android

我正在练习 Android 尝试制作一个带有多行文本的简单应用程序..

我试着从 kivy 开始写我知道如何写的文本,我以前读过这篇文章,使用

"""
text\n
another text
"""

这是 textView 代码:

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text=
            """
            onCreate(): Called by the OS when the activity is first created.\n
            This is where you initialize any UI elements or data objects.\n
            You also have the savedInstanceState of the activity that contains its previously saved state, and you can use it to recreate that state.
            """
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

好像不行,我试着写的明明白白的,比如:"Text\n Another Text" 它有效,但这真的很难完成,如果你正在处理很长的文本..

以防万一,这是我尝试的第二种方式的 textView 代码:

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="onCreate(): Called by the OS when the activity is first created. This is where you initialize any UI elements or data objects. You also have the savedInstanceState of the activity that contains its previously saved state, and you can use it to recreate that state."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

有没有一种方法可以像我第一种写法那样写?我是否需要使用另一种类型的文本或在此文本中添加一些内容?是不是我做错了什么导致第一种方法出错了?

在布局 xml 文件中使用硬编码字符串是不好的做法。

您可以在单独的 strings.xml 中定义字符串,该字符串应该已经在 res/values/strings 下的默认 android 项目中生成。xml

在这里您可以只定义字符串并根据需要在字符串中使用换行符。

例如

<string name="myString" > This is your string.

   This is the second line of your string.\n\n Third line of your string.</string>

您可以在其中使用实际的换行符或 \n。

然后分配给TextView喜欢

 android:text="@string/myString"