How to sum values in xml?

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

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