Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum values in xml?

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.

like image 445
Pooks Avatar asked Apr 23 '14 06:04

Pooks


2 Answers

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.

like image 96
Yashika Avatar answered Nov 15 '22 11:11

Yashika


Now this is partly possible with Data Binding

  1. Enable data binding

  2. 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()
    }
    
  3. 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}"/>
    
like image 43
Pavel Berdnikov Avatar answered Nov 15 '22 12:11

Pavel Berdnikov