androidtextviewboldfont-style

Set some text bold in textview, but not everything


Is there any possibility to set some text bold. For example:

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="all"
            android:textColor="#000000"
            android:textColorLink="#004c93"
            android:text="Hello everyone, I am Max!"/>

"Hello everyone," should have a normal font-style, but "I am Max!" should be bold. Is there anyway like in html I can use <strong></strong>?

I have a text with about 400 rows and the text is located in the values directory and more precisely in the strings.xml.


Solution

  • From the Android docs: https://developer.android.com/reference/android/text/style/StyleSpan

     SpannableString string = new SpannableString("Bold and italic text");
     string.setSpan(new StyleSpan(Typeface.BOLD), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
     string.setSpan(new StyleSpan(Typeface.ITALIC), 9, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    Then call textView.setText(string); like you normally would.

    EDIT: You can also try using HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY); which also returns a Spanned of its own.

    However, if you're putting this html as a string resource, you will need to escape some XML characters.