DataBinding with Android Dialog

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

Here is the code I 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 this is an Activity , we can execute DataBindingUtil.setContentView() , and for Fragment we can execute DataBindingUtil.inflate() , but I'm confused how to convert dialog.setContentView(R.layout.layout_terms); with DataBinding .

+6
source share
1 answer

Assuming this is something like 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 need to get Binding . This is done by simply inflating:

 /* * 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 termsBinding.getRoot() as ContentView :

 dialog.setContentView(termsBinding.getRoot()); 

And you're done. :)

+4
source

All Articles