Warm tip: This article is reproduced from stackoverflow.com, please click
android android-layout

How to actually re-use UI layout elements?

发布于 2020-03-27 10:16:07

To make sure every UI element of the same type looks the same, I am trying to find a way to re-use layout elements for proper way. For example, my primary CTA button always has a rounded background, font, text size, spacing, color, etc.

I could use the <include/> tag like so:

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

with my include_primary_button.xml being:

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

Using the <include/> tag limits only the layout properties to be overridden. So for example setting the text of every button used, I need to findViewById in the activity/fragment and set the text programmatically. This annoys me, but can be overcome. But then retrieving the button from the activity (eg. Button mButton = findViewById(R.id.activity_home_cta);), the button is null. What is missing here?

And is there not an easier way to re-use elements? This really feels like a hassle.

Questioner
jerome2710
Viewed
156
Oya 2019-07-03 21:17

You can make a style. For example

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

And then add it

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

If you want to have a custom view you can always create a new class that will extend from whatever you want (ex, Button, View) which will have its own xml and then you would add it like so. (Here is a tutorial for that. There are many on the interwebz)

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