如何在 Android TextView 中添加换行符?

发布于 2024-10-24 08:52:58 字数 488 浏览 16 评论 0原文

我正在尝试在 TextView 中添加换行符。

我尝试了建议 \n 但这没有任何作用。这是我设置文本的方法。

TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));

这是我的字符串: some test line 1 \n some test line 2

它应该显示如下:

some test line 1
some test line 2

但它显示如下: 一些测试线1一些测试线2

我错过了什么吗?

I am trying to add a line break in the TextView.

I tried suggested \n but that does nothing. Here is how I set my texts.

TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));

This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>

It should show like so:

some test line 1
some test line 2

But it shows like so: some test line 1 some test line 2.

Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

话少心凉 2024-10-31 08:52:59

\n 对我有用,如下所示:

<TextView android:text="First line\nNext line"

\n works for me, like this:

<TextView android:text="First line\nNext line"
花期渐远 2024-10-31 08:52:59

好的,明白了:

<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>

所以用 CDATA 换行是必要的,并且将中断作为 html 标签添加到内部

ok figured it out:

<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>

so wrap in CDATA is necessary and breaks added inside as html tags

酒解孤独 2024-10-31 08:52:59

Android 1.6 版本无法识别\r\n。
相反,使用: System.getProperty("line.separator")

String s = "Line 1"
           + System.getProperty("line.separator")
           + "Line 2"
           + System.getProperty("line.separator");

Android version 1.6 does not recognize \r\n.
Instead, use: System.getProperty("line.separator")

String s = "Line 1"
           + System.getProperty("line.separator")
           + "Line 2"
           + System.getProperty("line.separator");
紫﹏色ふ单纯 2024-10-31 08:52:59

换行符 (\n) 在将字符串资源值放在引号中时才起作用,如下所示:

<string name="sample_string">"some test line 1 \n some test line 2"</string>

如果您不将字符串资源值放在引号中,则不会进行换行:

<string name="sample_string">some test line 1 \n some test line 2</string>

是的,就是这么简单。

Linebreaks (\n) only work if you put your string resource value in quotes like this:

<string name="sample_string">"some test line 1 \n some test line 2"</string>

It won't do linebreaks if you put it without quotes like this:

<string name="sample_string">some test line 1 \n some test line 2</string>

yes, it's that easy.

森末i 2024-10-31 08:52:59

尝试了上述所有方法,做了一些我自己的研究,得出了以下用于渲染换行转义字符的解决方案:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. 使用需要过滤转义换行的替换方法(例如“\\n”)

  2. 只有这样,换行符'\n'转义字符的每个实例才会呈现为实际的换行

对于此示例,我使用了包含 JSON 格式数据的 Google Apps 脚本 noSQL 数据库 (ScriptDb)。

干杯:D

Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. Using the replace method you need to filter escaped linefeeds (e.g. '\\n')

  2. Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed

For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.

Cheers :D

你的他你的她 2024-10-31 08:52:59

有两种方法可以解决这个问题。
如果您使用字符串作为原始字符串,则需要使用换行符
特点。如果您将其用作 html,例如通过使用 Html.fromString 解析它,
第二种变体更好。

1) 换行符 \n

<string name="sample">This\nis a sample</string>

2) Html 换行符

<string name="sample">This<br>is a sample</string>

There are two ways around this.
If you use your string as a raw string, you need to use the newline
character. If you use it as html, e.g. by parsing it with Html.fromString,
the second variant is better.

1) Newline character \n

<string name="sample">This\nis a sample</string>

2) Html newline tag <br> or <br />

<string name="sample">This<br>is a sample</string>
韶华倾负 2024-10-31 08:52:59

这对我有用

android:text="First \n Second"

This worked for me

android:text="First \n Second"
怂人 2024-10-31 08:52:59

这对我有用,也许有人会发现这有帮助:

TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");

This worked for me, maybe someone will find out this helpful:

TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");
嘿看小鸭子会跑 2024-10-31 08:52:59

如果您使用 XML 声明 TextView,请使用 android:singleLine = "false" 或在 Java 中使用 txtSubTitle.setSingleLine(false);

If you're using XML to declare your TextView use android:singleLine = "false" or in Java, use txtSubTitle.setSingleLine(false);

七堇年 2024-10-31 08:52:59

使用Android Studio 0.8.9。对我有用的唯一方法是使用 \n
使用 CDATA 包装、

都不起作用。

Used Android Studio 0.8.9. The only way worked for me is using \n.
Neither wrapping with CDATA nor <br> or <br /> worked.

风吹短裙飘 2024-10-31 08:52:59

我使用以下内容:

YOUR_TEXTVIEW.setText("Got some text \n another line");

I use the following:

YOUR_TEXTVIEW.setText("Got some text \n another line");
吻泪 2024-10-31 08:52:59

非常简单:使用“\n”

    String aString1 = "abcd";
    String aString2 = "1234";
    mSomeTextView.setText(aString1 + "\n" + aString2);

\n 对应于 ASCII 字符 0xA,即“LF”或换行符

\r 对应于 ASCII 字符 0xD,即“CR”或回车

符 这可以追溯到第一台打字机,其中您可以选择仅进行换行(并仅键入下一行),或者在 Android / java 上进行换行 + 回车(也移动到行首)

\n 对应于回车 + 行feed,否则你只会“覆盖”同一行

very easy : use "\n"

    String aString1 = "abcd";
    String aString2 = "1234";
    mSomeTextView.setText(aString1 + "\n" + aString2);

\n corresponds to ASCII char 0xA, which is 'LF' or line feed

\r corresponds to ASCII char 0xD, which is 'CR' or carriage return

this dates back from the very first typewriters, where you could choose to do only a line feed (and type just a line lower), or a line feed + carriage return (which also moves to the beginning of a line)

on Android / java the \n corresponds to a carriage return + line feed, as you would otherwise just 'overwrite' the same line

も让我眼熟你 2024-10-31 08:52:59

据我所知,在 android studio 的早期版本中使用单独的行“\n”代码。但新版本(4.1.2)使用“

<string name="string_name">Sample text 1 \n Sample text 2 </string>

新的:

<string name="string_name">Sample text 1 <br/> Sample text 2 </string>

As I know in the previous version of android studio uses separate lines " \n " code. But new one (4.1.2) uses "<br/" to separate lines. For example -
Old one:

<string name="string_name">Sample text 1 \n Sample text 2 </string>

New one:

<string name="string_name">Sample text 1 <br/> Sample text 2 </string>
初雪 2024-10-31 08:52:59

您还可以添加 "<br/>" 而不是 \n。

这是
的 HTML 转义代码

然后你可以向TexView添加文本:

articleTextView.setText(Html.fromHtml(textForTextView));

Also you can add "<br/>" instead of \n.

It's HTML escaped code for <br/>

And then you can add text to TexView:

articleTextView.setText(Html.fromHtml(textForTextView));
叹倦 2024-10-31 08:52:59

尝试仔细检查您的本地化。
有可能,您尝试编辑一个文件(本地化),但实际上使用另一个文件进行编程,就像我的情况。默认系统语言是俄语,而我尝试编辑英语本地化。

就我而言,工作解决方案是使用“\n”作为行分隔符:

    <string name="string_one">line one.
    \nline two;
    \nline three.</string>

Try to double-check your localizations.
Possible, you trying to edit one file (localization), but actually program using another, just like in my case. The default system language is russian, while I trying to edit english localization.

In my case, working solution is to use "\n" as line separator:

    <string name="string_one">line one.
    \nline two;
    \nline three.</string>
以歌曲疗慰 2024-10-31 08:52:59

您还可以使用 Android Studio 的字符串编辑器,它会自动生成线刹车之类的东西......

You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...

帅冕 2024-10-31 08:52:59

由于 Html.fromHtml 已弃用,我只是使用此代码在下一行中获取 String2 。

textView.setText(fromHtml("String1 <br/> String2"));

@SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html){
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }

As Html.fromHtml deprecated I simply I used this code to get String2 in next line.

textView.setText(fromHtml("String1 <br/> String2"));

.

@SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html){
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }
幽梦紫曦~ 2024-10-31 08:52:59

最简单的方法是转到值/字符串(在您的资源文件夹中),

在那里声明一个字符串:

    <string name="example_string">Line 1\Line2\Line n</string>

在您的特定 xml 文件中,只需调用该字符串即可

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/example_string" />

The most easy way to do it is to go to values/strings (in your resource folder)

Declare a string there:

    <string name="example_string">Line 1\Line2\Line n</string>

And in your specific xml file just call the string like

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/example_string" />
痕至 2024-10-31 08:52:59

我找到了另一种方法:
需要添加“android:maxWidth="40dp"”属性。
当然,它可能无法完美工作,但它会产生换行符。

I found another method:
Is necessary to add the "android:maxWidth="40dp"" attribute.
Of course, it may not work perfectly, but it gives a line break.

唠甜嗑 2024-10-31 08:52:59

\n 不适合我。我能够通过将 xml 更改为文本并构建 textview 文本属性来解决该问题,如下所示。

android:text="Line 1
Line 2
Line 3

DoubleSpace"

希望这可以帮助那些说 \n 对他们不起作用的人。

\n was not working for me. I was able to fix the issue by changing the xml to text and building the textview text property like below.

android:text="Line 1
Line 2
Line 3

DoubleSpace"

Hopefully This helps those who have said that \n did not work for them.

娜些时光,永不杰束 2024-10-31 08:52:59

我正在从文件中读取文本,因此我采取了稍微不同的方法,因为将 \n 添加到文件中会导致 \n 出现在文本中。

    final TextView textView = (TextView) findViewById(R.id.warm_up_view);
    StringBuilder sb = new StringBuilder();
    Scanner scanner = new Scanner(getResources().openRawResource(R.raw.warm_up_file));
    while (scanner.hasNextLine()) {
      sb.append(scanner.nextLine());
      sb.append("\n");
    }

    textView.setText(sb.toString());

I'm reading my text from a file, so I took a slightly different approach, since adding \n to the file resulted in \n appearing in the text.

    final TextView textView = (TextView) findViewById(R.id.warm_up_view);
    StringBuilder sb = new StringBuilder();
    Scanner scanner = new Scanner(getResources().openRawResource(R.raw.warm_up_file));
    while (scanner.hasNextLine()) {
      sb.append(scanner.nextLine());
      sb.append("\n");
    }

    textView.setText(sb.toString());
柠栀 2024-10-31 08:52:59

就我而言,我通过添加以下内容解决了这个问题:

android:inputType="textMultiLine"

In my case, I solved this problem by adding the following:

android:inputType="textMultiLine"
苍景流年 2024-10-31 08:52:59

也许您可以将 lf 放入文本中,但它不显示?确保控件有足够的高度。例如:

正确:

android:layout_height="wrap_content"

可能错误:

android:layout_height="10dp"

Maybe you are able to put the lf into the text, but it doesn't display? Make sure you have enough height for the control. For example:

Correct:

android:layout_height="wrap_content"

May be wrong:

android:layout_height="10dp"
陌生 2024-10-31 08:52:59

我觉得需要一个更完整的答案来描述它是如何更彻底地工作的。

首先,如果您需要高级格式,请查看如何使用 HTML 的手册在字符串资源中
然后你可以使用
等。但是,这需要使用代码设置文本。

如果只是纯文本,有很多方法可以在 static 字符串资源

将字符串括在双引号中

最简洁的方法是将字符串括在双引号中。
这将使空白被完全解释为它出现的样子,而不是折叠。
然后您可以简单地在此方法中正常使用换行符(不要使用缩进)。

<string name="str1">"Line 1.
Line 2.
Line 3."</string>

请注意,在此模式下某些字符需要特殊转义(例如 \")。

下面的转义序列也适用于引号模式。

当在 XML 中使用单行表示多行字符串

时在 XML 中转义换行符的优雅方法是使用其 XML/HTML 实体 及其代码点(十六进制的 10 或 0xA)。这是转义任何字符的 XML 方式
然而,这似乎只在引用模式下有效。

另一种方法是简单地使用 \n ,尽管在我看来它会对易读性产生负面影响(因为它不是 XML 中的特殊转义序列,Android Studio 不会突出显示它)。

<string name="str1">"Line 1.
Line 2.
Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>

不要在任何这些转义序列之后包含换行符或任何空格,因为这将被解释为额外的空格。

I feel like a more complete answer is needed to describe how this works more thoroughly.

Firstly, if you need advanced formatting, check the manual on how to use HTML in string resources.
Then you can use <br/>, etc. However, this requires setting the text using code.

If it's just plain text, there are many ways to escape a newline character (LF) in static string resources.

Enclosing the string in double quotes

The cleanest way is to enclose the string in double quotes.
This will make it so whitespace is interpreted exactly as it appears, not collapsed.
Then you can simply use newline normally in this method (don't use indentation).

<string name="str1">"Line 1.
Line 2.
Line 3."</string>

Note that some characters require special escaping in this mode (such as \").

The escape sequences below also work in quoted mode.

When using a single-line in XML to represent multi-line strings

The most elegant way to escape the newline in XML is with its code point (10 or 0xA in hex) by using its XML/HTML entity or . This is the XML way to escape any character.
However, this seems to work only in quoted mode.

Another method is to simply use \n, though it negatively affects legibility, in my opinion (since it's not a special escape sequence in XML, Android Studio doesn't highlight it).

<string name="str1">"Line 1.
Line 2.
Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>

Do not include a newline or any whitespace after any of these escape sequences, since that will be interpreted as extra space.

夜吻♂芭芘 2024-10-31 08:52:59

我建议查询 line.separator 属性,并在您想要添加换行符时使用该属性。

这是一些示例代码:

TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+"  line2" );

I would recommend querying the line.separator property, and using that whenever you want to add a line break.

Here is some sample code:

TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+"  line2" );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文