首页 > 解决方案 > Android,重用不是布局,而是通过 XML 重用视图

问题描述

我有一个在我的布局中经常使用的按钮。或者更确切地说,我有十个按钮,它们都具有相同的文本颜色、背景颜色、文本大小、宽度和高度。我不想为每个按钮定义所有这些参数。所以我希望能够写出类似...

<include view="@layout/standard_button"
    android:id="@+id/button-id"
    android:text="button-specific-text"/>

但是当然,没有 include view="",只有 include 布局,并且将xml文件包含布局为 Layout,而不是 View,因此无法设置文本,当我findViewById()在我的活动中时,它会引用 Layout 而不是一个看法。

有没有类似的东西<include view="...

标签: androidxmlandroid-layout

解决方案


您可以使用要多次使用的自定义样式按钮创建布局,并将其包装在<merge>如下示例的标签中。

include然后,您可以在任何其他布局中使用该标签一遍又一遍地重复使用它。

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

在任何其他布局中使用,假设顶部布局命名为my_button.xml

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

推荐阅读