DataBinding With Android Dialog

Ravi picture Ravi · Jul 11, 2016 · Viewed 7.6k times · Source

I have implemented DataBinding in Activity, Fragment and RecyclerView. Now trying to do it in Dialog, but little bit confuse about how to set custom view inside it?

Here is code i have implemented for Dialog.

Dialog dialog = new Dialog(context);
dialog.getWindow();

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

LayoutTermsBinding termsBinding;

dialog.setContentView(R.layout.layout_terms);
dialog.getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

dialog.show();

I know if it is Activity we can perform DataBindingUtil.setContentView() and for Fragment we can perform DataBindingUtil.inflate() but i am confuse about how to convert dialog.setContentView(R.layout.layout_terms); with DataBinding.

Answer

yennsarah picture yennsarah · Jul 11, 2016

Assuming something like this is your layout_terms.xml:

<layout>
    <data>
        <!--You don't even need to use this one, this is important/necessary for the inflate method -->
        <variable name="testVariable" value="String" /> 
    </data>
    <LinearLayout>
        <TextView />
    </LinearLayout>
</layout>

First, you'll need to get your Binding. This is done by simply inflating it:

/*
* This will only work, if you have a variable or something in your 'layout' tag, 
* maybe build your project beforehand. Only then the inflate method can be found. 
* context - the context you are in. The binding is my activities binding. 
* You can get the root view somehow else.
*/
LayoutTermsBinding termsBinding = LayoutTermsBinding
    .inflate(LayoutInflater.from(context), (ViewGroup) binding.getRoot(), false);

 //without a variable this would be
LayoutTermsBinding termsBinding = DataBindingUtil.
      inflate(LayoutInflater.from(context), R.layout.layout_terms, (ViewGroup) mainBinding.getRoot(), false);

Second step: Set your termsBinding.getRoot() as ContentView:

dialog.setContentView(termsBinding.getRoot());

And you're done. :)