带有自定义视图的android数据绑定 [英] android data binding with a custom view

查看:34
本文介绍了带有自定义视图的android数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

在您的自定义视图中,按照您通常的方式扩展布局并为您要设置的属性提供一个 setter:

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 创建了一个自动绑定属性,因为有一个名为 setMyViewModel 的 setter.

In the above, an automatic binding attribute is created for app:myViewModel because there is a setter with the name setMyViewModel.

这篇关于带有自定义视图的android数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆