3

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 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer! Also, if you happen to have a setter method on your ComplexCustomPicker that takes the PickerViewModel, then you don't need the BindingAdaper. Android Data Binding automatically tries to find something with the name setXxx where Xxx is the attribute. So if ComplexCustomPicker has a method void setViewModel(PickerViewModel), you can use the attribute app:viewModel="@{viewModel}" just like above. This technique means that you're tying your view to your model types, but that may be fine in your app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.