Skip to content Skip to sidebar Skip to footer

Android Databinding In Custom Controls

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

Solution 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"})
publicstaticvoidbindCustomView(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"?><layoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/tools"><data><variablename="viewModel"type="com.pkgname.ViewModel"/></data>

    // Your layout

    <com.pkgname.CustomView 
    // Otherattributesapp:viewmodel="@{viewModel}"
    /></layout>

And from your Activity use this to set the ViewModel:

MainActivityBindingbinding= DataBindingUtil.setContentView(this, R.layout.main_activity);
ViewModelviewModel=newViewModel();
binding.setViewModel(viewModel);

Or you can directly inflate from your custom view:

LayoutViewCustomBindingbinding= DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_view_custom, this, true);
ViewModelviewModel=newViewModel();
binding.setViewModel(viewModel);

Post a Comment for "Android Databinding In Custom Controls"