android - 使用 Android 对话框进行数据绑定(bind)

标签 android data-binding android-dialog android-databinding

我在ActivityFragmentRecyclerView 中实现了DataBinding。现在尝试在 Dialog 中执行此操作,但对如何在其中设置自定义 View 有点困惑?

这是我为 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();

我知道如果它是 Activity 我们可以执行 DataBindingUtil.setContentView() 并且对于 Fragment 我们可以执行 DataBindingUtil.inflate () 但我对如何将 dialog.setContentView(R.layout.layout_terms);DataBinding 转换感到困惑。

最佳答案

假设您的 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>

首先,您需要获取Binding。这是通过简单地对其充气来完成的:

/*
* 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);

第二步:将您的 termsBinding.getRoot() 设置为 ContentView:

dialog.setContentView(termsBinding.getRoot());

你就完成了。 :)

关于android - 使用 Android 对话框进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299626/

相关文章:

c# - windows store app Listview 绑定(bind)

c# - 为什么不能将 Windows 窗体的大小绑定(bind)到 ApplicationSettings?

wpf - WPF 样式的绑定(bind)

android - 在没有任何引用的情况下获取一个打开的对话框

java - 将android项目添加到git

java - onKeyDown 仅使用退格键触发

android - 如何在android中显示如图所示的自定义错误对话框?

android - android中带有复选框和按钮的快速操作对话框/弹出窗口

Android 应用程序用户登录 Activity

android - 将 APK 文件从构建位置复制到 gradle 4.4 中的其他位置