Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to set XML dimen variables programatically

Tags:

android

layout

In my layout XML files, I reference a lot of parameters through a separate files called dimens.xml.

For example, dimens.xml contains parameters like these:

<dimen name="textSize_normal">20dp</dimen>
<dimen name="buttonTextSize_normal">15dp</dimen>
<dimen name="editTextSize_normal">17dp</dimen>
<dimen name="buttonHeight_normal">37dp</dimen>
<dimen name="margin_normal">5dp</dimen>

And in my main.xml, for example, I would set the text size for a TextView by doing something like this:

android:textSize="@dimen/editTextSize_normal"

It works great.

Now, my questions is, is it possible to set the values for the dimen variables in my dimen.xml file programmatically from my main activity? What I am trying to do is fetch the screen size, and set, for example, the textSize based on a fraction of the height of the screen so that it is easily adaptable to any screen size. I have all that figured out, I just need your help to figure out how to set the dimen variables in my code.

like image 506
capcom Avatar asked Aug 18 '12 14:08

capcom


1 Answers

Now, my questions is, is it possible to set the values for the dimen variables in my dimen.xml file programmatically from my main activity?

No.

What I am trying to do is fetch the screen size, and set, for example, the textSize based on a fraction of the height of the screen so that it is easily adaptable to any screen size.

Ignoring that this is an odd UI approach, the way to do that is to delete your android:textSize attributes and to change the text size at runtime using setTextSize() in Java.

I have all that figured out, I just need your help to figure out how to set the dimen variables in my code.

You don't "set the dimen variables". You apply your calculations to the widgets, via setters like setTextSize().

like image 65
CommonsWare Avatar answered Nov 12 '22 23:11

CommonsWare