Bold words in a string of strings.xml in Android

前端 未结 9 2095
甜味超标
甜味超标 2020-12-01 02:44

I have a long text in one of the strings at strings.xml. I want to make bold and change the color of some words in that text.

How can I do it?

相关标签:
9条回答
  • 2020-12-01 03:10

    In Kotlin I have created an extension function for the Context. It takes a @StringRes and optionally you can provide parameters as well.

    fun Context.fromHtmlWithParams(@StringRes stringRes: Int, parameter : String? = null) : Spanned {
    
        val stringText = if (parameter.isNullOrEmpty()) {
                        this.getString(stringRes)
                    } else {
                        this.getString(stringRes, parameter)
                    }
    
        return Html.fromHtml(stringText, Html.FROM_HTML_MODE_LEGACY)
    
    }
    

    Usage

    tv_directors.text = context?.fromHtmlWithParams(R.string.directors, movie.Director)
    
    0 讨论(0)
  • 2020-12-01 03:12

    strings.xml

    <string name="sentence">This price is <b>%1$s</b> USD</string>
    

    page.java

    String successMessage = getText(R.string.message,"5.21");
    

    This price 5.21 USD

    0 讨论(0)
  • 2020-12-01 03:14

    Strings.xml

    <string name="my_text"><Data><![CDATA[<b>Your text</b>]]></Data></string>
    

    To set

    textView.setText(Html.fromHtml(getString(R.string.activity_completed_text)));
    
    0 讨论(0)
提交回复
热议问题