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

Rav*_*avi 7 data-binding android android-dialog android-databinding

我已经实现DataBindingActivity,FragmentRecyclerView.现在尝试进行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();
Run Code Online (Sandbox Code Playgroud)

我知道这是不是Activity我们可以执行DataBindingUtil.setContentView()Fragment可以执行DataBindingUtil.inflate(),但我混淆如何转换dialog.setContentView(R.layout.layout_terms);DataBinding.

yen*_*rah 6

假设这样的事情是你的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>
Run Code Online (Sandbox Code Playgroud)

首先,你需要得到你的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);
Run Code Online (Sandbox Code Playgroud)

第二步:设置termsBinding.getRoot()ContentView:

dialog.setContentView(termsBinding.getRoot());
Run Code Online (Sandbox Code Playgroud)

而且你已经完成了.:)