我正在构建一个复杂的布局,我想为我的自定义组件使用 include
标签,如下所示:
<include layout="@layout/topbar"/>
topbar
布局具有自定义根组件,在布局 xml 文件中定义如下:
<my.package.TopBarLayout
... a lot of code
现在,我想将自定义属性传递给“topbar”,如下所示:
<include layout="@layout/topbar" txt:trName="@string/contacts"/>
然后在自定义组件代码或理想情况下在 xml 中获取这些自定义属性的值。
遗憾的是,我无法获取 txt:trName
属性的值以使其进入 topbar
布局,我只是没有收到任何代码。如果我从 that documentation page 正确理解,我可以为通过 include
使用的布局设置任何属性,但 id
、height
和 width
。
所以我的问题是如何将自定义属性传递给通过 include
添加的布局?
最佳答案
我知道这是一个老问题,但我发现它现在可以通过数据绑定(bind)来实现。
首先您需要启用 Data Binding在你的项目中。使用 DataBindingUtil.inflate
(而不是 setContentView
,如果它是 Activity
)使其工作。
然后将数据绑定(bind)添加到要包含的布局中:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="title" type="java.lang.String"/>
</data>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/screen_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="center">
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textStyle="bold"
android:text="@{title}"/>
...
</RelativeLayout>
</layout>
最后,将变量从主布局传递到包含的布局,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
...
</data>
...
<include layout="@layout/included_layout"
android:id="@+id/title"
app:title="@{@string/title}"/>
...
</layout>
关于android - 包括具有自定义属性的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11265258/