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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With