Search code examples
androidtextviewtext-sizescreen-density

Getting weird font size after setting it programmatically


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?


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.