How to reuse components?

Viewed 1194

I create an UI for my Android app. I use Android Studio, java and xml.

I designed a generic button component that looks like this:

enter image description here

One should be able to configure text colour, icon (image) and button text of this button.

Then I want to take this button component and create a navigation bar component that consists of two buttons:

enter image description here

Finally I want to take the navigation component, configure icons, text colours and texts for buttons and use it in my activity's layout to have a navigation bar like this:

enter image description here

Can you please show me an example how we can I achieve this? I have some experience with Qt Quick and creating components like this in Qt Quick is so easy and straightforward. I hope something similar is achievable also with Android's xml.

I spent an hour trying to create this using include tag and data binding, without any luck.

2 Answers

You can either create a "Custom View" which extends the existing Button class or you can create a "Compound View" which just groups multiple views into one reusable component. A compound view usually extends a container class (like LinearLayout or ConstraintLayout. You can then pass a XML layout into it or create the required views inside your compound view.

In order to customize your new (compound) view, you can declare styleable attributes.

To get you started with custom views, you can check out the lessons 10.1 and 10.2 of the Codelabs for Advanced Android Development

A tutorial and example for compound views can be found here.

Note, that in both cases, you can create an XML file in your resources folder which contains additional attributes for your custom / compound view. This will allow you to set e.g. custom icons for your view in XML.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomStyle">
        <attr name="titleText" format="string" localization="suggested" />
        <attr name="valueColor" format="color" />
    </declare-styleable>

</resources>

In the code of your custom / compound view, you can then read the information via the obtainStyledAttributes method in the constructor.

public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.MyCustomStyle, 0, 0);
    String titleText = a.getString(R.styleable.MyCustomStyle_titleText);
}

(Example taken from vogella.com)

You could just save it as an resource xml in the Drawables folder and then simply use it and also change the color of it using the android:backgroundTint="*COLOR OF YOUR CHOOSING*". I mean you would use it for buttons so just include the xml in the background of the button

Related