在官方的android文档中-有关如何在片段和 Activity 中使用数据绑定的一些指导。但是,我有相当复杂的选择器,具有大量的设置。就像是:

class ComplexCustomPicker extends RelativeLayout{
    PickerViewModel model;
}

所以我的问题是我需要重写选择器的哪种方法才能在其中使用绑定而不设置/检查文本字段等单个值?

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

最佳答案

我认为使用自定义设置器将解决您的问题。开发人员指南中的Check this section

我可以举一个简短的例子。假设您的视图名称为CustomView,而视图模型的名称为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);

07-24 09:47
查看更多