android数据绑定与自定义视图 [英] android data binding with a custom view
问题描述
Android数据绑定指南讨论了活动或片段中的绑定值,但是在那里一种使用自定义视图执行数据绑定的方法?
The Android data binding guide discusses binding values within an activity or fragment, but is there a way to perform data binding with a custom view?
我想做一些类似于
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mypath.MyCustomView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="40dp"/>
</LinearLayout>
与 my_custom_view.xml
:
<layout>
<data>
<variable
name="myViewModel"
type="com.mypath.MyViewModelObject" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{myViewModel.myText}" />
</LinearLayout>
</layout>
虽然可以通过在自定义视图中设置自定义属性来做到这一点,但这将很快变得麻烦如果有很多值要绑定。
While it appears possible to do this by setting custom attributes on the custom view, this would quickly become cumbersome if there's a lot of values to bind.
有没有一个很好的方法来完成我想要做的事情?
Is there a good way to accomplish what I'm trying to do?
推荐答案
在您的自定义视图中,放大布局,但您通常会为您要设置的属性设置一个设置器:
In your Custom View, inflate layout however you normally would and provide a setter for the attribute you want to set:
private MyCustomViewBinding mBinding;
public MyCustomView(...) {
...
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBinding = MyCustomViewBinding.inflate(inflater);
}
public void setMyViewModel(MyViewModelObject obj) {
mBinding.setMyViewModel(obj);
}
然后在布局中使用它:
<layout xmlns...>
<data>
<variable
name="myViewModel"
type="com.mypath.MyViewModelObject" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mypath.MyCustomView
android:id="@+id/my_view"
app:myViewModel="@{myViewModel}"
android:layout_width="match_parent"
android:layout_height="40dp"/>
</LinearLayout>
</layout>
在上面,为app:myViewModel创建一个自动绑定属性,因为有一个setter与名称setMyViewModel。
In the above, an automatic binding attribute is created for app:myViewModel because there is a setter with the name setMyViewModel.
这篇关于android数据绑定与自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!