2

I have TextView and I want each word of the text to be with different size and font.

I know that you can set part of the text to be bold or with underline with the and tags.

But what if I need part of the text to be the size of 18sp and have a custom typeface(from assets) and another part to have a different custom typeface and a size of 14sp.

I can split the TextView to individual TextViews, but I want to avoid that.

user1940676
  • 4,348
  • 9
  • 44
  • 73

2 Answers2

8

You should use RelativeSizeSpan ,for Reference RelativeSizeSpan for different font sizes.

TextView tv;
final SpannableString text = new SpannableString("Hello World");
text.setSpan(new RelativeSizeSpan(2.0f), 0, 5,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new RelativeSizeSpan(1.5f), 5, 11,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(text);

For FontStyle use StyleSpan for reference StyleSpan

So use can use custom typeface with the help of StyleSpan.

text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), start,
                    end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

Hope this will help you.

Amit Gupta
  • 8,914
  • 1
  • 25
  • 33
  • I used AbsoluteSizeSpan as you can set the text size in px, rather than RelativeSizeSpan which sets the proportion of text size. – Kalimah Jul 01 '16 at 14:38
0

You can write your code in HTML with all the styling you like and then use Html.fromHtml() in the setText() method:

E.g.:

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

Or:

Refer to this question. it might help you: Custom Textview with Html text and Custom Font whole Android application

Community
  • 1
  • 1
Basant Singh
  • 5,736
  • 2
  • 28
  • 49