2

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.

Max
  • 183
  • 1
  • 5
  • 18

2 Answers2

4

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.

Khodor
  • 129
  • 1
  • 7
  • Is there a chance to use "lines" instead of "symbols" ? – Max Jan 17 '20 at 18:35
  • I assume you mean formatting by line as opposed to formatting per word/character? If so, I doubt there's an easy, out-of-the-box solution. Since `TextView` itself decides how many lines the string will be rendered into. You might have to implement a workaround yourself. Maybe this will help: https://stackoverflow.com/questions/15679147/how-to-get-line-count-of-textview-before-rendering – Khodor Jan 17 '20 at 18:58
  • Otherwise, a less robust solution would be inserting the line breaks yourself. – Khodor Jan 17 '20 at 18:59
0

There is an Html class which help us use Html text in android view

Just like this

textview.setText(Html.fromHtml("Hello everyone, <strong>I am Max!</strong>"));

this will look like this

Hello everyone, I am Max!

Rahul sharma
  • 1,492
  • 12
  • 26
  • Ty for your answer but my text has about 400 lines and I get it from a string.xml file – Max Jan 17 '20 at 14:18