android - 包括标签和数据绑定(bind)

标签 android xml android-layout android-databinding

我想使用 include 在同一个 View 中多次使用我的布局之一。假设我有一个 custom.xml 包括一些 TextView

custom.xml:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

我在 parent.xml 中多次包含此布局:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/custom"
        android:id="@+id/layout1"/>

    <include layout="@layout/custom"
        android:id="@+id/layout2"/>
</LinearLayout>

现在我想将我的数据模型绑定(bind)到这个布局,但问题是我不知道如何将两个不同的数据模型绑定(bind)到 layout1layout2因为它们都来自一种布局,即 custom.xml。据我所知,我可以在我的 xml 布局中添加这个标签:

    <data>
       <variable name="user" type="com.myproject.model.User"/>
   </data>

但我需要将两个不同的数据模型绑定(bind)到 custom.xml

我的问题是如何在一个 View 中多次包含布局并使用数据绑定(bind)将不同的数据传递给它们?类似于将数据传递给布局但不将模型静态绑定(bind)到 xml。

我还找到了 this完全相同的问题但是由于数据绑定(bind)是在较新版本的android中发布的,所以我正在寻找一种使用数据绑定(bind)解决相同问题的方法。这是我为澄清而引用的那个问题的一部分:

For instance, I have a carefully crafted layout that I want to display three times in my view. Every of those instances would need different values. Since the include is basically a take that XML and paste it here, I'd need something more powerful.

最佳答案

您可以从 parent.xml 传递它

<include layout="@layout/custom"
    android:id="@+id/layout1"
    app:user="@{object of user1`}"/>

<include layout="@layout/custom"
    android:id="@+id/layout2"
    app:user="@{object of user2`}"/>

这里需要通过User来自 parent.xml 的对象

确保您拥有 <data>在 custom.xml 中

<data>
   <variable name="user" type="com.myproject.model.User"/>
</data>

Here与此相关的详细答案,引用它

关于android - 包括标签和数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867165/

相关文章:

如果没有设置背景颜色,Android获取父 View 的背景颜色

android - Flutter 深度链接

xml - XSLT 合并节点

javascript - jQuery附加不包含子元素的div

java - 跳过 49 帧!应用程序可能在其主线程上做了太多工作

java - Android - 进度条不更新

android - 我需要在 proguard.cfg 中放入什么来启用混淆?

java - 使用 XSLT 的 CDATA XML 屏蔽应返回相同的 XML,但屏蔽字段很少

android - 布局设计中缺少属性 - Android Studio

android:layout_weight 意外行为?