繁体   English   中英

使用相同的数据绑定上下文分解复杂的XML布局

[英]Breaking down complex XML layouts using the same data-binding context

语境

Android中的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

数据绑定库文档中

通过使用应用程序名称空间和属性中的变量名称,可以将变量从包含的布局传递到包含布局的绑定中:

 <?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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM