使用Android数据绑定,可以在包含的布局上设置变量,如此(从文档中):
<?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>
我在尝试使用ViewStub
时传递变量时做了同样的事情,但它不起作用。为什么ViewStub
不像包含布局那样工作?
答案 0 :(得分:1)
将数据传递到ViewStub
正在按预期工作。您定义命名空间并在该命名空间中传递变量,并在<variable>
布局中将其作为常规ViewStub
接受,如下所示:
main_layout.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my-namespace="http://schemas.android.com/apk/res-auto">
<data>
<variable name="myData" type="com.example.SomeModel" />
</data>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ViewStub
android:id="@+id/view_stub"
android:inflatedId="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/another_layout"
my-namespace:data="@{myData}"
/>
</RelativeLayout>
</layout>
another_layout.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<!-- No need to declare my-namespace here -->
<data>
<variable name="data" type="com.example.SomeModel" />
</data>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{data.someValue}" />
</RelativeLayout>
</layout>
答案 1 :(得分:0)
ViewStub
在Data Binding Library documentation中被称为不同。
<强> ViewStubs 强>
ViewStubs与普通视图略有不同。它们开始是不可见的,当它们被显示或被明确告知要膨胀时,它们会通过膨胀另一个布局来替换它们。
由于ViewStub基本上从View层次结构中消失,因此绑定对象中的View也必须消失以允许收集。由于视图是最终的,因此ViewStubProxy对象取代了ViewStub,使开发人员在ViewStub存在时可以访问ViewStub,并且在ViewStub膨胀时也可以访问膨胀的View层次结构。
在为另一个布局充气时,必须为新布局建立绑定。因此,ViewStubProxy必须侦听ViewStub的ViewStub.OnInflateListener并在那时建立绑定。由于只有一个可以存在,ViewStubProxy允许开发人员在其上设置一个OnInflateListener,它将在建立绑定后调用它。