包含具有自定义属性的布局 [英] Include layout with custom attributes

查看:89
本文介绍了包含具有自定义属性的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了复杂的布局,并为自己的自定义组件使用了"include",例如

I making complex layout and I using "include" for my custom component, like this

<include layout="@layout/topbar"/>

顶部栏定义如下:

<?xml version="1.0" encoding="utf-8"?>
<my.package.TopBarLayout
 ... a lot of code

现在,我想像这样将我的自定义定义的属性传递给"topbar"

Now, I wanna pass my custom defined attributes to "topbar" like this

<include layout="@layout/topbar" txt:trName="@string/contacts"/>

但是我没有结果.我从该页面了解到,我不能设置任何属性,但可以设置id,高度和宽度

But I have no result. I understood from that page that I can set no attributes, but id, height and width.

那么,如何传递自定义定义的属性包括在内?如何使它起作用?

So, how can I pass my custom defined attributes to include, and how can I make it work?

推荐答案

我知道这是一个老问题,但是我碰到了它,发现由于数据绑定,现在有可能.

I know this is an old question but I came across it and found that it is now possible thanks to Data Binding.

首先,您需要在数据绑定中启用您的项目.

First you need to enable Data Binding in your project.

然后将数据绑定添加到要包括的布局中:

Then add data binding to the layout you want to include:

<?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>

最后,将变量从主布局传递到包含的布局,如下所示:

Finally, pass the variable from the main layout to the included layout like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
    ...
</data>    
...
xmlns:app="http://schemas.android.com/apk/res-auto"
...
<include layout="@layout/included_layout"
            android:id="@+id/title"
            app:title="@{@string/title}"/>
...
</layout>

这篇关于包含具有自定义属性的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆