简体   繁体   English

在 Android 中使用 AlertDialog.setMessage() 时如何将部分文本设置为粗体?

[英]How to set part of text to bold when using AlertDialog.setMessage() in Android?

How to set part of text to Bold when using AlertDialog 's setMessage() ?使用AlertDialogsetMessage()时如何将部分文本设置为粗体? Adding <b> and </b> to my String doesn't work.<b></b>到我的String中不起作用。

You need to use Html.fromHtml() too.您也需要使用Html.fromHtml() 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.看起来Html.fromHtml(String source)在最新的 Android Nougat 版本中已被弃用。 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) .替换为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 .有关更多详细信息,请查看此答案

This page describes how to add HTML formatting to resource strings. 本页介绍如何向资源字符串添加 HTML 格式。

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

And do not forget to use: Html.fromHtml并且不要忘记使用: Html.fromHtml

AlertDialog.setMessage(Html.fromHtml(getString(R.string.welcome_messages)));

This works for me这对我有用

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 .这些解决方案都不适合我,但我需要使用旧版本的 API,所以我不能使用Html.fromHtml To bold part of the text for an AlertDialog I had to use a SpannableString .为了将AlertDialog的文本部分加粗,我必须使用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.我并不是说这是最好的方法,但这是对我有用的方法。

<string name="abouttxt">"<b>Info</b>\ntexttxtxtxtxt"</string>

这在 xml 中对我有用

In case if anyone wants to add only a single string:如果有人只想添加一个字符串:

<string name="abouttxt">&lt;b>Enter license key&lt;/b></string>

Add this line in your Alertdialog code.在您的 Alertdialog 代码中添加这一行。

dialog.setTitle(Html.fromHtml(getString(R.string.abouttxt)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM