首页 > 解决方案 > 警报对话框:字符串未转换为粗体文本

问题描述

我已经查看了这个问题以帮助将粗体文本放入 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();
    }

标签: javaandroid

解决方案


使用可扩展的字符串,就像标题的字符串一样:

        SpannableString spannableString = new SpannableString(message);
        spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        text.setText(spannableString);

start 是第一个粗体字符的索引,length 是粗体字符串的长度。


推荐阅读