温馨提示:本文翻译自stackoverflow.com,查看原文请点击:android - How to actually re-use UI layout elements?
android android-layout

android - 如何实际重用UI布局元素?

发布于 2020-03-27 10:22:25

为了确保相同类型的每个UI元素看起来都相同,我想找到一种以适当方式重用布局元素的方法。例如,我的主要CTA按钮始终具有圆形的背景,字体,文本大小,间距,颜色等。

我可以<include/>像这样使用标签:

<include
    layout="@layout/include_primary_button"
    android:id="@+id/activity_home_cta" />

我的include_primary_button.xml存在:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <Button
        tools:ignore="MissingPrefix"
        fontPath="fonts/Roboto.ttf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button"
        android:text="STUB!"
        android:textAllCaps="true"
        android:textColor="@color/text"
        android:textSize="@dimen/text" />
</merge>

使用<include/>标记仅限制布局属性被覆盖。因此,例如设置每个使用的按钮的文本,我需要findViewById在活动/片段中以编程方式设置文本。这让我很烦,但是可以克服。但是然后从活动中检索按钮(例如Button mButton = findViewById(R.id.activity_home_cta);),则该按钮为null。这里缺少什么?

还有没有更简单的方法来重用元素?这真的感觉很麻烦。

查看更多

查看更多

提问者
jerome2710
被浏览
216
Oya 2019-07-03 21:17

您可以制作样式。例如

<style name="CustomButton" parent="@style/Widget.AppCompat.Button">
        <item name="android:minHeight">40dp</item>
        <item name="android:textAppearance">@style/ButtonText</item>
        <item name="android:textColor">@color/btn_primary</item>
        <item name="android:background">@drawable/btn_primary</item>
        <item name="android:paddingEnd">@dimen/btn_padding</item>
        <item name="android:paddingStart">@dimen/btn_padding</item>
    </style>

 <style name="ButtonText">
        <item name="android:textAllCaps">true</item>
        <item name="android:fontFamily">@font/arial</item>
        <item name="android:textSize">@dimen/text_button</item>
    </style>

然后添加

<Button
            style="@style/CustomButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/btn" />

如果您想拥有一个自定义视图,则始终可以创建一个新类,该类将从您想要的任何内容(例如,Button,View)扩展而来,并具有自己的xml,然后您可以像这样添加它。(这是一个教程。interwebz上有很多)

<CustomView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>