TextView – getTextSize() vs setTextSize()


I decided to resume publishing some of the Android related issues that I stumble upon and workarounds and fixes for these issues.

So today I need to reduce the text size of the TextView in code at runtime. Easy peasy, I thought.


Well, it didn’t work. Instead, the text size was now much much bigger then it was before. What? Bigger? Yes! But why?

That confusing thing behind this is that you have to realize that the two function have different measurement units as parameters and return values.

TextView.getTextSize()  returns the size in pixels and TextView.setTextSize(…)  expects the value to be in „scale independent pixels (SP)“.

So what I ended up doing is:

float oneSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1, getResources().getDisplayMetrics());
textView.setTextSize((textView.getTextSize()/oneSp) - 1);

Another approach would be to use the second function to set the text size which also accepts the unit, which would be TypedValue.COMPLEX_UNIT_PX  in this case:

textView.setTextSize(TypedValue.COMPLEX_TYPE_PX, textView.getTextSize() - 1);