Android数据绑定(bind): Why doesn't passing in variable to ViewStubs work like include layouts?

标签 android android-layout android-databinding

使用 Android 数据绑定(bind),可以在包含的布局上设置变量,如下所示(来自文档):

    <?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 不像包含布局那样工作?

最佳答案

将数据传递至ViewStub s 正在按预期工作。您定义 namespace 并在该 namespace 中传递变量,并将其作为常规 <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>

关于Android数据绑定(bind): Why doesn't passing in variable to ViewStubs work like include layouts?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099750/

相关文章:

android - 使节拍器精确为 android

android - 如何给android :startColor in gradient drawable in Android?添加主题属性

Android Jetpack 撰写 : Keyboard changing from numeric to alphabets after modifying input text

Android DataBinding float 到 TextView

android - 有什么 butterknife 可以做而数据绑定(bind)做不到的吗?

android - 使用 'bind' 和 'app' 命名空间设置自定义属性与 Android DB 之间的区别?

android - 告知 Android 设备何时处于 sleep 模式

android - 卸载我的应用程序后如何从 SD 卡中删除文件

java - 运营商 !参数类型 Object 未定义?

java - 为 Eclipse 设置 Android 支持包 v7 - GridLayout