android databinding in custom controls

霸气de小男生 提交于 2019-12-12 15:26:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!