我不知道如何使TextView上的特定文本变成粗体。

是这样的

txtResult.setText(id+" "+name);

我希望输出是这样的:

1111年尼尔

id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。


当前回答

如果你正在使用Kotlin,使用core-ktx会变得更容易,因为它提供了一种领域特定语言(DSL)来做这件事:

val string: SpannedString = buildSpannedString {
    bold {
        append("foo")
    }
    append("bar")     
}

它提供的更多选项有:

append("Hello There")
bold {
    append("bold")
    italic {
        append("bold and italic")
        underline {
            append("then some text with underline")
        }
    }
}

最后,你只需:

textView.text = string

其他回答

我创建了一个静态方法来设置文本粗体的TextView和EditText部分

public static void boldPartOfText(View mView, String contentData, int startIndex, int endIndex){
        if(!contentData.isEmpty() && contentData.length() > endIndex) {
            final SpannableStringBuilder sb = new SpannableStringBuilder(contentData);

            final StyleSpan bss = new StyleSpan(Typeface.BOLD); // Span to make text bold
            final StyleSpan iss = new StyleSpan(Typeface.NORMAL); //Span to make text normal
            sb.setSpan(iss, 0, startIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            sb.setSpan(bss, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
            sb.setSpan(iss,endIndex, contentData.length()-1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

            if(mView instanceof TextView)
               ((TextView) mView).setText(sb);
            else if(mView instanceof EditText)
               ((EditText) mView).setText(sb);

        }
    }

另一个更定制的代码

  /*typeFaceStyle can be passed as 

    Typeface.NORMAL = 0;
    Typeface.BOLD = 1;
    Typeface.ITALIC = 2;
    Typeface.BOLD_ITALIC = 3;*/

    public static void boldPartOfText(View mView, String contentData, int startIndex, int endIndex,int typeFaceStyle){
        if(!contentData.isEmpty() && contentData.length() > endIndex) {
            final SpannableStringBuilder sb = new SpannableStringBuilder(contentData);

            final StyleSpan bss = new StyleSpan(typeFaceStyle); // Span to make text bold
            final StyleSpan iss = new StyleSpan(Typeface.NORMAL); //Span to make text italic
            sb.setSpan(iss, 0, startIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            sb.setSpan(bss, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
            sb.setSpan(iss,endIndex,contentData.length()-1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);

            if(mView instanceof TextView)
                ((TextView) mView).setText(sb);
            else if(mView instanceof EditText)
                ((EditText) mView).setText(sb);
        }
    }

我用这个代码来加粗特定的单词…

    Spanned string = Html.fromHtml("Normal string <b>BOLD STRING</b>");
    textView.setText(string);

找到了一种方法,如果你想处理多种语言的本地化,这很无聊,但它是有效的,让我们假设我们想要这样:

英文:

没有付款记录

西班牙语:

没有付款记录

你必须创建3个字符串

中文:

<string name="start_string">There are no</string>
<string name="middle_string">payments</string>
<string name="end_string">registered.</string>
<string name="string_format" translatable="false">%1$s %2$s %3$s</string>

西班牙语:

<string name="start_string">No hay</string>
<string name="middle_string">pagos</string>
<string name="end_string">registrados</string>

现在你可以这样做:

val startSpanPosition = getString(R.string.start_string).length
val endSpanPosition = startSpanPosition + getString(R.string.middle_string).length
val mySpannableString = SpannableStringBuilder(String.format(getString(R.string.string_format),
        getString(R.string.start_string), getString(R.string.middle_string))), getString(R.string.end_string)))

mySpannableString.setSpan(StyleSpan(Typeface.BOLD), spanStartPosition, endSpanPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

以防有人使用数据绑定。我们可以像这样定义绑定适配器

@BindingAdapter("html")
fun setHtml(view: TextView, html: String) {
    view.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY))
}

然后我们可以在TextView上使用它

app:html="@{@string/bold_text}"

bold_text在哪里

<string name="bold_text"><![CDATA[Part of text is <b>bold</b>]]></string>

下面是我如何使用正则表达式和Kotlin来做到这一点

val BOLD_SPAN = StyleSpan(Typeface.BOLD)

    fun TextView.boldMatches(regexString: String) {
        this.applyStyleSpanToMatches(regexString, BOLD_SPAN)
    }
    

fun TextView.applyStyleSpanToMatches(regexString: String, span: StyleSpan){
        this.text = this.text.toString().applyStyleSpanToMatches(regexString, span)
        }

        fun String.applyStyleSpanToMatches(regexString: String, span: StyleSpan): Spannable {
            val result = SpannableString.valueOf(this)
            if(regexString.isEmpty()) return result
            val pattern = try{
                Pattern.compile(regexString)
            } catch (e: PatternSyntaxException){
                return result
            }
            val matcher = pattern.matcher(result)
            while (matcher.find()) {
                val start = matcher.start()
                val end = matcher.end()
                result.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            return result
        }

使用问句 它可以这样应用:

txtResult.boldMatches(id)