Skip to content Skip to sidebar Skip to footer

Using Variables In A String, To Do Html.fromhtml

Is there a way to use variables in this situation? I want this code: String str = 'test'; Html.fromHtml('test <.bold> str <./bold> test'); to make: test test test

Solution 1:

What about this?

Stringstr = "test";
textView.setText( Html.fromHtml("test <bold>" + str + "</bold> test") );

or for a more difficult solution, you can use java's replaceAll for replacing strings defined with regular expression.

Solution 2:

kotlin version using an extension function with Android SDK deprecation validation

@Suppress("deprecation")fun String.fromHtml(): Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
    Html.fromHtml(this)
}

val str = "test"
textView.text = "test <bold>$str</bold> test".fromHtml()

Post a Comment for "Using Variables In A String, To Do Html.fromhtml"