Arithmetic operations in layout - Android data binding

I am trying to use an arithmetic operation in data binding:

<Space
    android:layout_width="match_parent"
    android:layout_height="@{2 * @dimen/button_min_height}" />

Unfortunately, I get:

Error:(47, 47) must be able to find a common parent for int and float 

Any ideas?

+4
source share
2 answers

Since you are performing the operation int * float, a value of 2 is equal int, and @dimen/button_min_heightwill give you a value float. However, it android:layout_heightwill only take on value float.

You can create your own binding method as follows:

public class Bindings {
    @BindingAdapter("android:layout_height")
    public static void setLayoutHeight(View view, float height) {
       ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
       layoutParams.height = (int) height;
       view.setLayoutParams(layoutParams);
    }
}

and in your xml code

android:layout_height="@{(float)2 * @dimen/activity_vertical_margin}"

convert 2 to floatso that it doesn't give you any casting error.

From the code above you will get RunTimeException : You must supply a layout_height attribute.to solve this error, specify the defaultvaluelayout_height

android:layout_height="@{(float)2 * @dimen/activity_vertical_margin, default=wrap_content}"

default , ,

+7

. XML android: id :

<Space
    android:id="@+id/space"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Java :

Space space = findViewById(R.id.space);
space.getLayoutParams().height = 2 * getResources().getDimension(R.dimen.button_min_height);
space.requestLayout();
-2

Source: https://habr.com/ru/post/1648497/


All Articles