Different font size of strings in the same TextView
Use a Spannable String
String s= "Hello Everyone"; SpannableString ss1= new SpannableString(s); ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color TextView tv= (TextView) findViewById(R.id.textview); tv.setText(ss1);
Snap shot
You can split string using space and add span to the string you require.
String s= "Hello Everyone"; String[] each = s.split(" ");
Now apply span
to the string
and add the same to textview
.
Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan
instead of a RelativeSizeSpan
.
Just get the dimension in pixels of the desired text size
int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);
and then create a new AbsoluteSpan
based on the text
String text1 = "Hi";String text2 = "there";SpannableString span1 = new SpannableString(text1);span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);SpannableString span2 = new SpannableString(text2);span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);// let's put both spans together with a separator and allCharSequence finalText = TextUtils.concat(span1, " ", span2);