Android-查找子字符串并将其设为粗体

Coo*_*tor -2 android text textview

找到str1作为str2的子字符串,使其变为粗体(即在str2中),然后将其显示为textview的正确方法是什么?

Fer*_*med 5

使用str2SpannableString和使用setSpan()方法找到子串str1,使之BOLD

请参阅文档

尝试这个:

    TextView textView = (TextView) findViewById(R.id.textView);

    String str1 = "substring";
    String str2 = "Find a substring and make it bold";

    if (str2.contains(str1)) {

        SpannableString spannable = new SpannableString(str2);
        spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 
                str2.indexOf(str1), 
                str2.indexOf(str1) + str1.length(), 
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        textView.setText(spannable);
    } else {
        textView.setText(str2);
    }
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

希望这会有所帮助〜