Home » Android » Arithmetic operations in layout – Android Data Binding

Arithmetic operations in layout – Android Data Binding

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to use arithmetic operation in data binding:

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

Unfortunately I’m getting:

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

Any ideas?

How to&Answers:

Because you are performing int * float operation, 2 is int value and @dimen/button_min_height will give you float value. However android:layout_height will accept float value only.

You can create your custom binding method like this :

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 into float so it will not give you any casting error.

From above code you will get RunTimeException : You must supply
a layout_height attribute.
, inorder to solve that error, provide default value to layout_height

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

Refer this official docs for default attribute concept, or you can refer this answer as well

Answer:

You should do this programmatically. In your xml file add android:id attribute to your Space view :

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

In your Java class you should wirte this :

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