JoJo JoJo - 1 year ago 63
Android Question

How do I apply mathematical operations to Android dimensions?

How do I avoid this hardcoded math...

<dimen name="uno">10dip</dimen>
<dimen name="dos">6dip</dimen>
<dimen name="uno_plus_dos">16dip</dimen>

android:layout_marginTop="@dimen/uno_plus_dos" />

...and covert it to something like this?

android:layout_marginTop="@dimin/uno + @dimen/dos" />

Answer Source

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.