我认为使用自定义设置器可以解决您的问题。检查此部分 https://developer.android.com/topic/libraries/data-binding/index.html?hl=en#custom_setters在开发者指南中。
我可以给你一个简短的例子。假设您的视图名称是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);