【问题标题】:DataBinding With Android Dialog使用 Android 对话框进行数据绑定
【发布时间】:2016-11-12 23:15:00
【问题描述】:

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

这是我为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感到困惑。

【问题讨论】:

  • 有趣的问题。
  • 为什么不用DialogFragment?

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


【解决方案1】:

假设这样的事情是你的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());

你就完成了。 :)

【讨论】:

  • 有细微的变化,你可能忘记了,我已经添加了我的答案。
  • 但是,如果我包含了我的视图,你的答案是绝对正确的,但是我在这里使用对话框,因此它将在另一个 xml 文件中,并且不能将它包含在我的主 xml 中。
  • 我在我的代码中写了一个注释,你需要在你的&lt;data&gt;标签中使用一个变量来使用它。如果您会发布更多信息,我也可以为您提供您的解决方案。 ;)
  • 是的,但是我在我的问题中提到我希望在我的对话框中绑定以设置自定义视图,所以显然该视图不能包含在 xml 中,或者我不能在&lt;data&gt; 中使用它跨度>
  • 无论如何,你的回答给了我一些提示,我已经找到了解决方案,谢谢:)
猜你喜欢
  • 2011-09-05
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
相关资源
最近更新 更多