【问题标题】:How do multiline text in AndroidAndroid中的多行文本如何处理
【发布时间】:2022-01-04 09:03:56
【问题描述】:

我正在练习 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" />

有没有一种类似于我第一种写法的写法?我是否需要使用另一种类型的文本或在此文本中添加一些内容?是否有什么我做错了导致第一种方式错误。

【问题讨论】:

  • 第一个是正确的,因为应用不知道你什么时候要换行
  • 或者解压成字符串资源会更易读。
  • 感谢@GuanHongHuang ,我希望这种android studio 方式能长期有效,因为这与我通常的做法不同,似乎需要更长的时间,再次感谢。

标签: android kotlin text textview


【解决方案1】:

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

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

您可以在这里定义字符串并在字符串中随意使用换行符。

例如

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

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

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

然后赋值给TextViewlike

 android:text="@string/myString"

【讨论】:

  • 感谢@IvoBeckers,但我不太明白你写的第一个代码,请在“”中解释一下。您也许可以使用我的 textView 向我解释。我对此真的很陌生。再次感谢您的帮助..
  • 谢谢我现在知道你了..
猜你喜欢
  • 2013-05-23
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 2021-02-24
  • 2017-07-26
  • 2016-03-08
  • 1970-01-01
相关资源
最近更新 更多