Bold words in a string of strings.xml in Android

前端 未结 9 2128
甜味超标
甜味超标 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)
    

提交回复
热议问题