安卓自定义控件中的数据绑定

3

在官方的Android文档中,有一些指导如何在片段和活动中使用数据绑定。然而,我有一个非常复杂的选择器,有很多设置选项。类似这样:

class ComplexCustomPicker extends RelativeLayout{
    PickerViewModel model;
}

我的问题是,我需要重写选择器的哪种方法才能在其中使用绑定而不是设置/检查单个值,例如textfield等?

第二个问题-我如何将viewmodel传递给xml文件中的选择器,我需要一些自定义属性吗?

1个回答

3
我认为使用自定义Setter可以解决您的问题。请参考开发人员指南中的这个章节
我可以给你一个简单的例子。假设你的视图名称是CustomView,你的ViewModel的名称是ViewModel,那么在你的任何一个类中,创建一个像这样的方法:
@BindingAdapter({"bind:viewmodel"})
public static void bindCustomView(CustomView view, ViewModel model) {
    // Do whatever you want with your view and your model
}

在您的布局中,执行以下操作:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.pkgname.ViewModel"/>
    </data>

    // Your layout

    <com.pkgname.CustomView 
    // Other attributes
    app:viewmodel="@{viewModel}"
    />

</layout>

在你的Activity中使用以下代码设置ViewModel:

MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);

或者您可以直接从自定义视图中进行膨胀:

LayoutViewCustomBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_view_custom, this, true);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);

5
好的回答!此外,如果您在 ComplexCustomPicker 上有一个接受 PickerViewModel 的 setter 方法,那么您就不需要使用 BindingAdapter。Android 数据绑定会自动查找名称为 setXxx(其中 Xxx 是属性名)的内容。因此,如果 ComplexCustomPicker 有一个方法 void setViewModel(PickerViewModel),您可以像上面一样使用属性 app:viewModel="@{viewModel}"。这种技术意味着您将视图与模型类型绑定在一起,但在您的应用程序中可能是可以接受的。 - George Mount

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接