Different font size of strings in the same TextView Different font size of strings in the same TextView android android

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

enter image description here

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


You can get this done using html string and setting the html to Textview using
txtView.setText(Html.fromHtml("Your html string here"));

For example :

txtView.setText(Html.fromHtml("<html><body><font size=5 color=red>Hello </font> World </body><html>"));`