【问题标题】:Java android: appending a newline using TextViewJava android:使用 TextView 添加换行符
【发布时间】:2011-09-03 17:27:15
【问题描述】:

我只是想以某种方式在我的线性布局中添加一个新行:

layout = (LinearLayout) findViewById (R.id.layout);  

... //some other code where I've appended some strings already

final TextView nline = new TextView(this);
nline.setText(Html.fromHtml("<br>")); //i also tried:  nline.setText("\n");
layout.addView(nline);

但这只是增加了几个空格。有人可以帮我吗?谢谢。

【问题讨论】:

  • nline.setText(Html.fromHtml("
    "));如果添加 nline.setSingleLine(false);
    将正常工作

标签: java android textview newline


【解决方案1】:

首先,您需要将TextView 设为多行。然后使用简单的"\n" 字符串进行换行。

final TextView nline = new TextView(this);
nline.setSingleLine(false);
nline.setText("first line\n"+"second line\n"+"third line");

【讨论】:

  • 如果是\n\n 呢?在这种情况下,之后的一切都将被切断。
【解决方案2】:

如果您只想在其他两个视图之间留出一些空白空间,您可以在您的 XML 中执行此操作(假设您使用 XML 进行布局)。像这样的东西可以工作,基本上是放置一个具有透明背景和给定高度的视图。这是假设您在 TextView 中具有所需的任何参数。

<TextView />

<View android:background="#00000000"
      android:layout_height="12dp" //or whatever density pixel height you want
      android:layout_width="fill_parent" />

<TextView />

此外,在您上面尝试的内容中...您可以尝试使用空格和换行符...这可能会起作用。

nline.setText(" \n");

【讨论】:

  • 有趣,没有其他人提到'\n'之前的空格,谢谢Maximus :)
【解决方案3】:

您可能需要使用 TextView 的 setInputType() 方法将 InputType 设置为 TYPE_TEXT_FLAG_MULTI_LINE

tv.setInputType(tv.getInputType()|InputType.TYPE_TEXT_FLAG_MULTI_LINE);

您也可以在其他视图上设置一些边距/填充。我认为 TextViews 不应该被误用为分隔符。

【讨论】:

    【解决方案4】:

    简单如下:

    String hello = getResources.getString(R.string.hello);
    String world = getResources.getString(R.string.world);
    textView.setText(hello + "\n" + world);
    

    【讨论】:

      【解决方案5】:

      简单的通过给出“\n”数据在新行中显示

      txtView.setText("Latitude :" + latitude + "\nLongitude :" + longitude);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-19
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多