How to add a line break in an Android TextView?

2019-01-03 08:40发布

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?

21条回答
孤傲高冷的网名
2楼-- · 2019-01-03 09:12

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;
    }
查看更多
Animai°情兽
3楼-- · 2019-01-03 09:12

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.

查看更多
▲ chillily
4楼-- · 2019-01-03 09:13

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

查看更多
家丑人穷心不美
5楼-- · 2019-01-03 09:13

I use the following:

YOUR_TEXTVIEW.setText("Got some text \n another line");
查看更多
对你真心纯属浪费
6楼-- · 2019-01-03 09:14

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

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-03 09:14

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" />
查看更多
登录 后发表回答