Android数据绑定集alignParentTop [英] Android databinding set alignParentTop
问题描述
我有以下布局(仅保留相关部分):
I have following layout (only relevant parts left):
<RelativeLayout>
<View android:layout_alignParentTop="true"/>
</RelativeLayout>
我尝试使用<data>
块中声明的变量设置layout_alignParentTop
属性,如下所示:
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>
但是,当尝试进行编译时,android studio会显示以下内容:
However when trying to compile, android studio says the following:
错误:找不到参数类型为java.lang.Boolean的属性"android:layout_alignParentTop"的设置器.
Error: Cannot find the setter for attribute 'android:layout_alignParentTop' with parameter type java.lang.Boolean.
如何设置具有数据绑定变量的layout_alignParentTop
属性?
How can I set layout_alignParentTop
attribute with databinding variable?
推荐答案
I had to do some digging into this and I found a recent issue in Google Code.
引用项目成员之一:
我们明确不支持布局属性的数据绑定, 尽管您可以从技术上自己添加它们.问题是 尝试为它们设置动画的人很容易滥用这些.
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);
}
在您的情况下,您只需要针对alignParentTop
属性对其稍作调整:
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.
这篇关于Android数据绑定集alignParentTop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!