2016-07-11 24 views
6

Zaimplementowałem DataBinding w Activity, Fragment i RecyclerView. Teraz próbuje to zrobić w Dialog, ale trochę mylić o tym, jak ustawić niestandardowy widok w nim?DataBinding z Androidem Dialog

Oto kod, który zaimplementowałem dla 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(); 

wiem, czy to jest Activity możemy wykonać DataBindingUtil.setContentView() i Fragment możemy wykonać DataBindingUtil.inflate() ale jestem mylić o tym, jak konwertować dialog.setContentView(R.layout.layout_terms); z DataBinding.

+1

Interesujące pytanie. – pRaNaY

+0

Dlaczego nie używasz DialogFragment? –

Odpowiedz

4

Zakładając coś takiego jest twój 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> 

Po pierwsze, musisz uzyskać Binding. Odbywa się to poprzez proste pompowania go:

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

Drugi etap: Określ termsBinding.getRoot() jak ContentView:

dialog.setContentView(termsBinding.getRoot()); 

I gotowe. :)

+0

Tak, działało, dziękuję. –

+0

Jest niewielka zmiana, możesz zapomnieć, dodałem moją odpowiedź. –

+0

Jednak twoja odpowiedź jest absolutnie poprawna, jeśli zawarłem mój widok, ale tutaj używam okna dialogowego, aby znaleźć się w innym pliku xml i nie mogę uwzględnić tego w moim głównym xml. –