Android使用粗体字符作为部分文本

时间:2014-10-30 09:31:57

标签: android

我想简单地使用<b>部分文字,例如HTML&amp; CSS,我的下面代码不正确。

textEdit.setText("<![CDATA[ <b>"+ "bold text" + " </b> ]]>" + " view other normal text" );

2 个答案:

答案 0 :(得分:5)

使用 SpannableString 将子字符串设置为粗体。

    String completeString = "<your complete string here>";
    String subString = "<the substring you want in bold>";
    SpannableString ss = new SpannableString(completeString);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
            ds.setTypeface(Typeface.DEFAULT_BOLD);
            ds.setColor(<color that you want>);
        }
    };

    if (completeString.indexOf(subString) > -1)
        ss.setSpan(clickableSpan, completeString.indexOf(subString), completeString.indexOf(subString) + subString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    textEdit.setText(ss, TextView.BufferType.SPANNABLE);

答案 1 :(得分:2)

使用以下代码: -

mTextBox.setText(Html.fromHtml("<b>" + Bold text+ "</b>" +  "<br />" + 
            "<small>" + Small one+ "</small>" + "<br />" + 
            "<small>" + Small two+ "</small>"));