androidspannablestringformatted-text

Make formatArg in string resource bold Andoid


I have String resource with format argument %s

<string name="string_name">Hello Mr. %s. I want to ...</string>

This string resource is localized, so has different length depending on locale and has to be in one TextView

I want to make formatArg %s bold style

I've tried html tag <string name="string_name">Hello Mr. <b>%s</b>. I want to ...</string>

I've tried annotation tag <string name="string_name">Hello Mr. <annotation style="bold">%s</annotation>. I want to ...</string>

I've created SpannableString and tried to set Span to this annotation

And no any effect to string argument after I set text to TextView

tvDescription.setText(getString(R.string.string_name, "formatArg"));

Is there a way to set style to the string argument in formatted string resource?


Solution

  • This is how i style the message of an AlertDialog:

    Spanned htmlAsSpanned = Html.fromHtml("Some html tags are working in here<br /><br />
    <b>this is bold text</b>");
    

    Edit: Or maybe this is what you are looking for. Their example is this:

    String text = getString(R.string.welcome_messages, "Roko Spark", 5);
    Spanned styledText = Html.fromHtml(text);
    
    textView.setText(styledText);
    

    In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the &lt; notation.

    <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>