Kategorien
Android

TextView – getTextSize() vs setTextSize()

komedi_1419026753657_984

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.

textView.setTextSize(textView.getTextSize-1);

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

 

Eine Antwort auf „TextView – getTextSize() vs setTextSize()“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.