Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operations in layout - Android Data Binding

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?

like image 425
Dawid Hyży Avatar asked Jul 20 '16 11:07

Dawid Hyży


People also ask

What is data binding in Android MVVM?

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. Layouts are often defined in activities with code that calls UI framework methods.

Which is better view binding or data binding in Android?

ViewBinding vs DataBindingThe main advantages of viewbinding are speed and efficiency. It has a shorter build time because it avoids the overhead and performance issues associated with DataBinding due to annotation processors affecting DataBinding's build time.

Which is the correct way to reference bound data in the XML layout?

Layout Binding expressions Expressions in the XML layout files are assigned to a value of the attribute properties using the “ @{} " syntax. We just need to use the basic syntax @{} in an assignment expression.


1 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

like image 134
Ravi Avatar answered Jan 04 '23 00:01

Ravi