Different font size of strings in the same TextView

Adriana Carelli picture Adriana Carelli · May 2, 2013 · Viewed 101.3k times · Source

I have a textView inside with a number (variable) and a string, how can I give the number one size larger than the string? the code:

TextView size = (TextView)convertView.findViewById(R.id.privarea_list_size);
if (ls.numProducts != null) {
    size.setText(ls.numProducts + " " + mContext.getString(R.string.products));
}

I want ls.numproducts has a size different from the rest of the text. How to do?

Answer

Raghunandan picture Raghunandan · May 2, 2013

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.