我查看了这个问题以帮助在 java 字符串中放置粗体文本。 Display string with bold letters in Dialog message
我使用了第二个答案,但公平地说,第一个答案也适用。
我想将我的文本加粗,但它没有显示为粗体,与某人在上一个问题中给出的答案相比,我不确定为什么我的文本没有显示为粗体。
这适用于 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 是加粗字符串的长度。
关于java - 警报对话框 : a string is not converting to bold text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50889300/