2017-07-31 40 views
0

上下文

Android中的XML佈局會變得複雜。因此,將它們分解成概念獨立的模塊是一種很好的做法。請看下面的例子:使用相同的數據綁定上下文分解複雜的XML佈局

主要佈局:

<layout> 
    <data> 
     <variable name="someVar" type="some.custom.Type"/> 
    </data> 

    <SomeLayout 
     ... 
     android:someAttribute="@{someVar.someProperty}" /> 

    <include layout="@layout/some_other_layout /> 
</layout> 

some_other_layout.xml

<SomeOtherLayout 
     ... 
     android:someOtherAttribute="@{someVar.someOtherProperty}" /> 

問題

是否有可能使用相同的數據綁定上下文(無論是內部<data> )在兩個分開的佈局(如在給出的例子中)?

這樣做會天真地導致java.lang.IllegalStateException

回答

1

Data Binding Library documentation

變量可以被傳遞到通過使用該應用程序的名稱空間和變量名中的一個屬性所包括的佈局的從含佈局結合:

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:bind="http://schemas.android.com/apk/res-auto"> 
    <data> 
     <variable name="user" type="com.example.User"/> 
    </data> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
     <include layout="@layout/name" 
      bind:user="@{user}"/> 
     <include layout="@layout/contact" 
      bind:user="@{user}"/> 
    </LinearLayout> 
</layout>