How to use data-binding in Dialog?

It is possible to use databinding in a Dialog, first to get the binding working on your Dialog you should inflate it first and pass it to the setContentView like this.

DialogOlaBookingConfirmedBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout. dialog_ola_booking_confirmed, null, false);
setContentView(binding.getRoot());

Then you can pass the viewModel:

binding.setViewModel(new ViewModel(this, event.olaBooking));

And now you can see it working.


You should not use DataBindingUtil for generated classes as said in Android Documentation

You should use generated binding class's inflate & bind method (MyDialogBinding.inflate).

public void showDialog(final Context context) {
    Dialog dialog = new Dialog(context);
    MyDialogBinding binding = MyDialogBinding.inflate(LayoutInflater.from(context));
    dialog.setContentView(binding.getRoot());
    dialog.show();
}

Can it be simpler? No!

Binding Document says for DataBindingUtil class's inflate method.

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation. DataBindingUtil.inflate(LayoutInflater.from(getContext()),R.layout.my_info_dialog_layout, null, false);

This is like finding binding generated class, when we have class already.

Instead use this

MyDialogBinding binding = MyDialogBinding.inflate(LayoutInflater.from(context));

or if you want make another class.

public class MyDialog extends Dialog {
    public MyDialog(@NonNull Context context) {
        super(context);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyDialogBinding binding = MyDialogBinding.inflate(LayoutInflater.from(getContext()));
        setContentView(binding.getRoot());
    }
}