capcom
capcom

Reputation: 3337

Android: How to set XML dimen variables programatically

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.

Upvotes: 9

Views: 17530

Answers (4)

herre
herre

Reputation: 11

i guess what you mean is to change the size depending on the device's screen size.. which can be made by creating multiple dimens.xml files in folders like values-hdpi, values-xhdpi, values-xxhdpi, values-mdpi,.. and then on runtime the compiler will choose the dimen depending on the dpi i actually didn't try this before but i read it here.. take a look at this: http://developer.android.com/guide/practices/screens_support.html#qualifiers

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006539

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().

Upvotes: 12

kristoffz
kristoffz

Reputation: 149

No, you can't edit the Resources files on runtime, they are already compiled and generated.

Upvotes: 7

user468311
user468311

Reputation:

You should use density independent pixels in all your resources, so that dimensions can adapt to screen size. You don't need to calculate that values at runtime. If you want to have a different layout for different screen sizes, then consider using multiple resource files.

Read this guide.

Upvotes: 1

Related Questions