How to set text size using dimension from xml at runtime programmatically?

Yura Shinkarev picture Yura Shinkarev · Jan 26, 2013 · Viewed 63.4k times · Source

In dimens.xml, I have:

<dimen name="text_medium">18sp</dimen>

In runtime, I get this value and set the text size of a text view:

int size = context.getResources().getDimensionPixelSize(R.dimen.text_medium);
textView.setTextSize(size).

On a 10″ tablet (1280 x 800), everything is ok; but on a phone (800 x 480), the text view has a very large font. On the tablet, the size equals 18; on the phone, it's 27.

If I set the size manually by:

textView.setTextSize(size)

the size is normal on both devices.

Answer

Kostek Poland picture Kostek Poland · May 23, 2013

Add dimension in dimens.xml:

   <dimen name="text_medium">18sp</dimen>

Set the size in code:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));