java - 警报对话框:字符串未转换为粗体文本
问题描述
我已经查看了这个问题以帮助将粗体文本放入 java 字符串中。 在 Dialog 消息中显示带有粗体字母的字符串
我使用了第二个答案,但公平地说,可以应用第一个答案。
我想加粗我的文本,但它没有显示为粗体,并且与有人给出的上一个问题中给出的答案相比,我不确定为什么我的文本没有显示为粗体。
这适用于 android 应用程序,消息的变量作为字符串参数传递,以在警报对话框中使用。
字符串,xml:
<resources>
<string name="bold_yellow"><![CDATA[<b>yellow</b>]]></string>
</resources>
在课堂里:
ShowRewardDialog("Test " + Html.fromHtml(getResources().getString(R.string.bold_yellow)) + " Bold");
下面是 showRewardDialog() 方法:
private void ShowRewardDialog(String message) {
final Dialog dialog = new Dialog(Content.this);
dialog.setContentView(R.layout.custom_dialog);
SpannableString title = new SpannableString("YOU GAINED A REWARD");
title.setSpan(new ForegroundColorSpan(Content.this.getResources().getColor(R.color.purple))
, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set the custom dialog components - text, image and button
TextView text = dialog.findViewById(R.id.dialog_text);
dialog.setTitle(title);
text.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
解决方案
使用可扩展的字符串,就像标题的字符串一样:
SpannableString spannableString = new SpannableString(message);
spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text.setText(spannableString);
start 是第一个粗体字符的索引,length 是粗体字符串的长度。
推荐阅读
- ruby-on-rails - 设计确认后发送欢迎电子邮件
- html - 使用列宽和内联块的最少两行
- java - 管理 JMS 消息到多个服务器的传递
- python - Python:如何在指定日期和时间之后遍历一组文件和grep日志
- html - HTML 区别 .jpg .JPG
- spring - 无法使用带有 QueryDSL 和 Web 支持的 Spring Data Repository 查询 Set 中的字段
- serialization - PyGtk 序列化
- c# - 如何将 ContentControl 转换为 PlainTextContentControl/访问 .Text 属性?
- python - 如何将 python 字节对象传递给 C++ 扩展?
- javascript - Javascript - 间隔未清除