简体   繁体   English

Android,重用不是布局,而是通过 XML 重用视图

[英]Android, Reusing Not Layouts, But Views via XML

I have a button I use a lot in one of my layouts.我有一个在我的布局中经常使用的按钮。 Or rather, I have like ten buttons all with the same text color, background color, text size, width, and height.或者更确切地说,我有十个按钮,它们都具有相同的文本颜色、背景颜色、文本大小、宽度和高度。 I don't want to define all of these parameters for each button.我不想为每个按钮定义所有这些参数。 So I want to be able to write something like...所以我希望能够写出类似...

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

But of course, there is no include view="" , there is only include layout, and include layout the xml file as a Layout, not a View, so setting the text is not possible and when I findViewById() in my activity, it would refer to a Layout and not a View.但是当然,没有 include view="" ,只有包含布局,并且包含布局xml文件作为布局,而不是视图,所以设置文本是不可能的,当我findViewById()在我的活动中,它指的是布局而不是视图。

Is there something like <include view="... ?有类似<include view="...东西吗?

You can create a layout with your customized style button that you want to use multiple times, and wrap it in a <merge> tag like below sample.您可以使用要多次使用的自定义样式按钮创建布局,并将其包装在<merge>标记中,如下例所示。

And then you can reuse it over and over again using the include tag in any other layout.然后,您可以在任何其他布局中使用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>

Usage within any other layout, assuming the top layout named as my_button.xml在任何其他布局中使用,假设顶部布局命名为my_button.xml

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM