How to set part of text to Bold when using AlertDialog
's setMessage()
? Adding <b>
and </b>
to my String
doesn't work.

- 19,522
- 20
- 117
- 184

- 3,112
- 5
- 28
- 41
5 Answers
You need to use Html.fromHtml()
too. For example:
AlertDialog.setMessage(Html.fromHtml("Hello "+"<b>"+"World"+"</b>"));
Update:
Looks like Html.fromHtml(String source)
has been deprecated in the Latest Android Nougat version. Although deprecation doesn't mean that you need to change your code now, but it's a good practice to remove deprecated code from your app as soon as possible.
The replacement is Html.fromHtml(String source, int flags)
. You just need to add an additional parameter mentioning a flag.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
AlertDialog.setMessage(Html.fromHtml("Hello "+"<b>"+"World"+"</b>", Html.FROM_HTML_MODE_LEGACY));
} else {
@Suppress("DEPRECATION")
AlertDialog.setMessage(Html.fromHtml("Hello "+"<b>"+"World"+"</b>"));
}
For more details have a look at this answer.

- 1,641
- 1
- 13
- 31

- 19,522
- 20
- 117
- 184
-
2PS:Works for TextView, havn't checked for AlertDialog. – 0xC0DED00D Mar 30 '12 at 01:07
-
1you can use HtmlCompat.fromHtml(string str , flag) where you can use HtmlCompat.FROM_HTML_MODE_LEGACY as the flag, so that you avoid os version checking – Aleyam Oct 16 '19 at 05:21
This page describes how to add HTML formatting to resource strings.
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.
</string>
</resources>
And do not forget to use: Html.fromHtml
AlertDialog.setMessage(Html.fromHtml(getString(R.string.welcome_messages)));
This works for me

- 1,391
- 2
- 15
- 22
In case if anyone wants to add only a single string:
<string name="abouttxt"><b>Enter license key</b></string>
Add this line in your Alertdialog code.
dialog.setTitle(Html.fromHtml(getString(R.string.abouttxt)))

- 2,534
- 2
- 13
- 20
None of these solutions worked for me, but I am required to use an older version of the API so I could not use Html.fromHtml
. To bold part of the text for an AlertDialog
I had to use a SpannableString
.
String msgPart1 = getString(R.string.PartOneOfMessage);
SpannableString msg = new SpannableString(msgPart1 + " " + boldTextString + " " + getString(R.string.PartTwoOfMessage));
msg.setSpan(new StyleSpan(Typeface.BOLD), msgPart1.length() + 1, msgPart1.length() + datumName.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
AlertDialog.setMessage(msg);
I am not saying this is the best way, but it was the way that worked for me.

- 1,054
- 1
- 12
- 32