使用Android对话框进行数据绑定

使用Android对话框进行数据绑定,android,data-binding,android-dialog,android-databinding,Android,Data Binding,Android Dialog,Android Databinding,我在活动、片段和回收视图中实现了数据绑定。现在尝试在对话框中执行此操作,但对如何在其中设置自定义视图有点困惑 下面是我为对话框实现的代码 Dialog dialog = new Dialog(context); dialog.getWindow(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.gr

我在
活动
片段
回收视图
中实现了
数据绑定
。现在尝试在
对话框
中执行此操作,但对如何在其中设置自定义视图有点困惑

下面是我为
对话框
实现的代码

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();

我知道如果它是
活动
我们可以执行
DataBindingUtil.setContentView()
,对于
片段
我们可以执行
DataBindingUtil.inflate()
,但我不知道如何转换
dialog.setContentView(R.layout.layou)数据绑定

进行编码,假设这是您的
布局\u 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>
第二步:将
termsBinding.getRoot()设置为
ContentView

dialog.setContentView(termsBinding.getRoot());

你完成了。:)

有趣的问题。为什么不使用DialogFragment?有一点变化,您可能会忘记,我已经添加了我的答案。但是,如果我包含了我的视图,您的答案是绝对正确的,但我在这里使用dialog,它将在另一个xml文件中,并且不能包含在我的主xml中。我在代码中作为注释编写,您需要在
标记中使用一个变量才能这样使用它。如果您能发布更多信息,我也可以为您提供解决方案是的,但我在问题中提到,我希望在对话框中使用绑定来设置自定义视图,因此很明显,视图不能包含在xml中,或者我不能在
中使用它。无论如何,您的回答给了我一些提示,我已经找到了解决方案,谢谢:)
dialog.setContentView(termsBinding.getRoot());