Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 664
Yura Shinkarev Avatar asked Jan 26 '13 18:01

Yura Shinkarev


People also ask

How do I set text size programmatically?

To set Android Button font/text size, we can set android:textSize attribute for Button in layout XML file. To programmatically set or change Android Button font/text size, we can pass specified size to the method Button. setTextSize(specific_size).

What is Dimen in XML?

Note: A dimension is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine dimension resources with other simple resources in the one XML file, under one <resources> element.


1 Answers

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)); 
like image 183
Kostek Poland Avatar answered Sep 16 '22 17:09

Kostek Poland