私はあなたの問題を解決するカスタムセッターを使用すると思います。開発者ガイドラインのCheck this section
私は簡単な例を挙げることができます。ビューの名前は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);
また、 'PickerViewModel'をとる' ComplexCustomPicker'にセッターメソッドがあるとしたら、 'BindingAdaper'は必要ありません。 Androidのデータバインディングは、setXxxという名前のものを自動的に検索しようとします.Xxxは属性です。したがって、 'ComplexCustomPicker'に' void setViewModel(PickerViewModel) 'メソッドがある場合は、上記のように' app:viewModel = "@ {viewModel}"という属性を使用することができます。この技術は、あなたのモデルタイプにあなたのビューを結びつけていることを意味しますが、それはあなたのアプリでうまくいくかもしれません。 –