Android – Find a substring and make it bold

What would be the correct way to find str1 as a substring of str2, make it bold (in str2, that is), and then display it as a textview?

Answer

Use str2 as SpannableString and use setSpan() method to find substring str1 and make it BOLD.

See documentation.

Try this:

    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);
    }

OUTPUT:

enter image description here

Hope this will help~

Leave a Reply

Your email address will not be published. Required fields are marked *