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