I have following layout (only relevant parts left):
<RelativeLayout>
<View android:layout_alignParentTop="true"/>
</RelativeLayout>
I tried setting layout_alignParentTop
attribute with variable declared in <data>
block as shown here:
<data>
<variable
name="condition"
type="Boolean"/>
</data>
<RelativeLayout>
<View android:layout_alignParentTop="@{condition}"/>
</RelativeLayout>
However when trying to compile, android studio says the following:
Error: Cannot find the setter for attribute 'android:layout_alignParentTop' with parameter type java.lang.Boolean.
How can I set layout_alignParentTop
attribute with databinding variable?
Using data binding can lead to faster development times, faster execution times and more readable and maintained code. Android data binding generates binding classes at compile time for layouts.
Yep, we don't use <layout> ViewBinding, because on DataBinding we must add that layout tag to generate Binding class and it's different with ViewBinding which automatically generates all layout to Binding class.
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.
Stay organized with collections Save and categorize content based on your preferences. The @={} notation, which importantly includes the "=" sign, receives data changes to the property and listen to user updates at the same time. // Avoids infinite loops.
I had to do some digging into this and I found a recent issue in Google Code.
To quote one of the project members:
We explicitly did not support data binding for layout properties, though you could technically add them yourself. The problem is that these can be easily abused with people trying to animate them.
To implement these for your application, create a binding adapter:
@BindingAdapter("android:layout_width") public static void setLayoutWidth(View view, int width) { LayoutParams layoutParams = view.getLayoutParams(); layoutParams.width = width; view.setLayoutParams(layoutParams); }
In your case you would just need to adjust it slightly for the alignParentTop
attribute:
@BindingAdapter("android:layout_alignParentTop")
public static void setAlignParentTop(View view, boolean alignParentTop) {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if(alignParentTop) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
}
view.setLayoutParams(layoutParams);
}
This is untested, but it should be enough to get you on the right track.
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