android数据绑定(bind)与自定义 View

标签 android data-binding custom-view

Android data binding guide讨论了 Activity 或 Fragment 中的绑定(bind)值,但是有没有办法使用自定义 View 执行数据绑定(bind)?

我想做这样的事情:

<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>

虽然可以通过在自定义 View 上设置自定义属性来做到这一点,但如果要绑定(bind)很多值,这很快就会变得很麻烦。

有什么好方法可以完成我想做的事情吗?

最佳答案

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

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

关于android数据绑定(bind)与自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34799622/

相关文章:

android - Apportable porting from Cocos2d 项目报错

android - FLAG_ACTIVITY_CLEAR_TOP 在通知部分不起作用

java - 尝试在 android 中的 Strings.xml 中的 textView 中设置图像

android - 无法使用数据绑定(bind)在包含的布局中传递颜色变量

c# - DateTimePicker 数据绑定(bind)

android - ScaleFactor 往往是一个

android - 在 Android 中的随机路径上为 imageview 设置动画

ios - iOS swift 中的自定义 View 导出在 View Controller 中不起作用

android - ListView 行高太小

silverlight - ItemSource 更改时在 TreeView 中展开 Root