Home > front end >  String formatting doesn't work when running application in Android device
String formatting doesn't work when running application in Android device

Time:09-16

I have a string formatted like this.

<string name="instructions" formatted="true">
    Follow these instructions.
    <br/><br/>
    1. Step 1.
    <br/><br/>
    2. Step 2.
    <br/><br/>
    3. Step 3.
</string>

In the designer preview, it looks like this.

enter image description here

When I run it in an emulator or real Android device, it looks like this.

enter image description here

How can I get the real device to look like the designer preview?

CodePudding user response:

Use \n instead of <br/> like below:

    <string name="instructions" formatted="true">
    Follow these instructions.
    \n\n
    1. Step 1.
    \n\n
    2. Step 2.
    \n\n
    3. Step 3.
    </string>

CodePudding user response:

Another approach, you can try to use Html.fromHtml() which is in Android SDK. For an instance, like this: (Kotlin extension method)

fun String.toHtml() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(this)
}

In strings.xml, the string looks like this:

<string name="instructions">Follow these instructions.<br/><br/>1. Step 1.<br/><br/>2. Step 2.<br/><br/>3. Step 3.</string>

Note: I trim the spaces, you can add what you want, such as color

How to use it?

In Fragment or Activity, using getString(R.string.instructions).toHtml() to get the Spanned and display it on UI. Don't worry, Spanned extends from CharSequence.

  • Related