Question

I am trying to set TextView font size programmatically.

txtView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

But when I check this size via

Toast.makeText(this, "txt: " + txtView.getTextSize(), Toast.LENGTH_SHORT).show();

The Toast shows that the size is "24" which is 50% larger then the one I set before.

I tested multiple values and always get the same result:

8 becomes 12
10 becomes 15
15 becomes 22.5
etc.

The font I am trying to set always becomes 50% larger.

Why is this happening? Where am I making a mistake?

Was it helpful?

Solution

I believe this is because TextView.getTextSize() returns the text size in pixels, not sp units, regardless of what unit type you used to set the text size in the first place.

Additionally, another SO thread discusses how to convert this to sp units.

OTHER TIPS

getTextSize() method returns text size in pixels. When you set the text in setTextSize() in sp units it's scaled according to your screen density ratio which is 1.5.

I haven't found a certain answer regarding this setTextSize() problem. So I have done some experiments of my own and found that density plays a key role here. You need to know what your device's density, before you attempt to use setTextSize(). If you don't get it, or if you get it wrong, then your texts will have funny and irritating size. Many times I have tried to increase the textsize by adding 1 or 2, but actually making the text drastically smaller!

After a full half day trial and error, I have come to the following solution that works for low, mid and high density devices equally.

    float size = textView.getTextSize();  // get the textsize of the TextView in pixels
    float density = getApplicationContext().getResources().getDisplayMetrics().density; // get the density of your device. Important!!
    textView.setTextSize((size/density)+1); //increase the textsize by 1
    textView.setTextSize((size/density)-1); //decrease the textsize by 1

Try it. I hope you won't be disappointed.

You can define your font size using a .xml file:

<resources>
    <dimen name="test">12dp</dimen>
</resources>

And then set it programmatically:

txtView.setTextSize(getResources().getDimension(R.dimen.test));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top