Suppose I have 2 dimension values defined in an XML file and want to define a 3rd value that is the sum of the other 2 values. Is there a way to do that in the XML file?
Here is an illustration of what I would like to do.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="top_element_size">10dp</dimen>
<dimen name="element_spacing">5dp</dimen>
<dimen name="bottom_element_top">@dimen/top_element_size + @dimen/element_spacing</dimen>
</resources>
And I would like to define android:layout_marginTop="@dimen/bottom_element_top"
for the bottom element in a frame
layout.
But it appears that @dimen/top_element_size + @dimen/element_spacing
is not legal.
You cannot perform arithmetic or logical operations in xml file. Dynamically you can retrieve the data from the xml and sum the values in java code, then set that value as parameters to your LinearLayout or FrameLayout or any other widget.
Now this is partly possible with Data Binding
Enable data binding
Write Binding Adapter for each tag where you want to use arithmetic.
Since @dimen/smth
returns float, adapter should take float:
@BindingAdapter("android:layout_marginTop")
fun setTopMargin(view: View, topMargin: Float) {
(view.layoutParams as ViewGroup.MarginLayoutParams).topMargin = topMargin.toInt()
}
Use it in layout (! not in resources)
<View
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="@{@dimen/top_element_size + @dimen/element_spacing}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With