Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply mathematical operations to Android dimensions?

How do I avoid this hardcoded math...

<resources>  <dimen name="uno">10dip</dimen>  <dimen name="dos">6dip</dimen>  <dimen name="uno_plus_dos">16dip</dimen> </resources>  <Button   android:layout_marginTop="@dimen/uno_plus_dos" /> 

...and covert it to something like this?

<Button  android:layout_marginTop="@dimin/uno + @dimen/dos" /> 
like image 390
JoJo Avatar asked Nov 11 '11 23:11

JoJo


People also ask

How does Android define Dimen?

A dimension is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of measure are supported by Android: dp.

How do you make Dimen?

To create another dimens. xml file, right click your res folder and choose New > Value resource file. Then write in dimens and choose Smallest Screen Width. Write in 600 for the width (7” tablet).


2 Answers

You don't, sorry. Layout XML files do not support expressions. You either:

  • Leave it as @dimen/uno_plus_dos, or
  • Set your margins in Java code, where you can replace a single resource with a bunch of extra lines of code, or
  • Write your own layout preprocessor that handles expressions like this

UPDATE The data binding library supports some operations in its expressions. I am uncertain if it can handle this specific scenario.

like image 114
CommonsWare Avatar answered Oct 07 '22 21:10

CommonsWare


One trick for simple addition is to use margin + padding.

like image 38
miguel Avatar answered Oct 07 '22 22:10

miguel