问题
In official android docs - there is some guidance how to use databinding in fragments and activities. However I have pretty complex picker with high ammount of settings. Something like:
class ComplexCustomPicker extends RelativeLayout{
PickerViewModel model;
}
So my question is what method of the picker I need to override to be able use binding inside it and not seting/checking individual values like textfield, etc?
And second question - how could I pass viewmodel to my picker in xml file, do I need some custom attributes for that?
回答1:
I think using Custom Setters will solve your problem. Check this section in developers guidelines.
I can give you a brief example for it. Suppose the name of your view is CustomView
and of your viewmodel is ViewModel
, then in any of your class, create a method like this:
@BindingAdapter({"bind:viewmodel"})
public static void bindCustomView(CustomView view, ViewModel model) {
// Do whatever you want with your view and your model
}
And in your layout, do the following:
<?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>
And from your Activity
use this to set the ViewModel:
MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);
Or you can directly inflate from your custom view:
LayoutViewCustomBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_view_custom, this, true);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);
来源:https://stackoverflow.com/questions/37965789/android-databinding-in-custom-controls