JoJo JoJo - 12 days ago 6
Android Question

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" />

Answer

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.