我想使用 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)到 layout1
和 layout2
因为它们都来自一种布局,即 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/