[英]Breaking down complex XML layouts using the same data-binding context
XML layouts in Android can get complicated. Android中的XML布局可能会变得复杂。 Hence, it is a good practice to break them down into conceptually independent modules.
因此,将它们分解为概念上独立的模块是一个好习惯。 Consider the following example:
考虑以下示例:
Main layout: 主要布局:
<layout>
<data>
<variable name="someVar" type="some.custom.Type"/>
</data>
<SomeLayout
...
android:someAttribute="@{someVar.someProperty}" />
<include layout="@layout/some_other_layout />
</layout>
and some_other_layout.xml
: 和
some_other_layout.xml
:
<SomeOtherLayout
...
android:someOtherAttribute="@{someVar.someOtherProperty}" />
Is it possible to use the same data-binding context (whatever is inside <data>
) in two separated layouts (like in the given example)? 是否可以在两个分开的布局中使用相同的数据绑定上下文(
<data>
任何内容)(如给定示例)?
Doing this naively results in java.lang.IllegalStateException
. 天真地执行此操作会导致
java.lang.IllegalStateException
。
From the Data Binding Library documentation : 从数据绑定库文档中 :
Variables may be passed into an included layout's binding from the containing layout by using the application namespace and the variable name in an attribute:
通过使用应用程序名称空间和属性中的变量名称,可以将变量从包含的布局传递到包含布局的绑定中:
<?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.