Table of contents
1.
Introduction
2.
Custom UI Components
2.1.
Example Application
3.
Frequently Asked Questions
4.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Custom UI Components in Android

Author Pradeep Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will look into the Custom UI Components in Android. Custom UI Components allow you to create a custom component according to your requirement that you can use in an android application.

In this article, we will be using the Android Studio application, so in case you haven't yet set up the application on your system, you can check out this article.

Custom UI Components

Android provides a large number of widgets such as ListView, Button, TextView, RadioButton, EditText, and others that you can use directly in your Android application. But there may be times when none of the pre-build widgets suits your needs. 

In that case, android provides us with the functionality of designing our own custom widgets which suit our requirements. Let's see how we can create a custom component with the help of an example.

Example Application

In this example, we will create a custom component to display the date and time. The custom component extends the TextView component to display the text on the screen.

First create a new file attributes.xml in the res/values folder. In this file, we have declared a declare-styleable with the name "DateTimeView". It contains the list of custom attributes that the DateTimeView will be needing.

attributes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DateTimeView">
        <attr name="dateTimeText" format="string" />
        <attr name="darkTheme" format="boolean"/>
    </declare-styleable>
</resources>

Now, we will create a new Kotlin file, DateTimeView.kt, in the same folder as your MainActivity.kt file. In this file, we have defined the methods for setting the values of the custom attributes in DateTimeView.

DateTimeView.kt

package com.example.customuicomponents

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import java.text.SimpleDateFormat
import java.util.*


class DateTimeView : androidx.appcompat.widget.AppCompatTextView {
    private var dateTimeText: String? = null
    private var darkTheme: Boolean? = false

    //constructor if only context is given
    constructor(context: Context?) : super(context!!) {
        setDateTimeView()
    }

    //constructor if attribute set is also given with context
    constructor(context: Context, attributes: AttributeSet?) : super(context, attributes) {
        // array
        val array = context.obtainStyledAttributes(
            attributes,
            R.styleable.DateTimeView
        )

        var i=0
        // iterate the array and check for specific attributes
        while(i< array.indexCount){
            val attributes = array.getIndex(i)

            //check if the current attribute is dateTimeText
            if (attributes == R.styleable.DateTimeView_dateTimeText) {
                // set datetime
                dateTimeText = array.getString(attributes)
                setDateTimeView()
            }
            //check if the current attribute is darkTheme
            else if (attributes == R.styleable.DateTimeView_darkTheme) {
                // check if the dark theme is requested or not
                darkTheme = array.getBoolean(attributes, false)
                setTheme() // set the theme
            }
            i++;
        }
    }

    private fun setDateTimeView() {
        // date time format
        val dateTimeFormat = SimpleDateFormat("hh:mm aa\ndd-MM-yyyy")
        // set the time
        val dateTime = dateTimeFormat.format(Calendar.getInstance().time)
        //set the text
        text = if (dateTimeText != null) dateTimeText + " " + dateTime else dateTime

    }

    private fun setTheme() {
        if (darkTheme == true) {
            // set background color as black
            setBackgroundColor(Color.BLACK)
        }
        else{
            //set background color as yellow
            setBackgroundColor(Color.YELLOW)
        }
    }
}

Now, to render the DateTimeView, we need to add the component to the activity_main.xml file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.example.customuicomponents.DateTimeView
        android:id="@+id/dateTimeView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="50sp"
        custom:darkTheme="true"
        custom:dateTimeText="" />
</RelativeLayout>

MainActivity.kt file is the entry point for this android application. 

MainActivity.kt:

package com.example.customuicomponents

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

// MainActivity extending the AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Output:

As we have mentioned the value of custom:darkTheme as "true" in the activity_main.xml file, the background color of the custom component is rendered as black.

Frequently Asked Questions

  1. What should be the initial step in creating a new custom component?
    The first step is to design the component's layout. The layout specifies how the component will look on the screen.
     
  2. What is a compound component?
    A compound component is made by combining several components. Layouts are typically used to create a compound component to control how the components are arranged on the screen.
     
  3. Can we create a custom component by overriding the methods of pre-built widgets?
    Yes, a custom component can be created by overriding the methods of widgets such as TextView. You can override their in-build methods to render the output as per your requirements on the screen.

Check this out : usb debugging

Conclusion 

In this article, we have extensively discussed the Custom UI Components in Android and their implementation in Android Studio. We discussed how Custom UI Components could be created and registered in an android application.

We hope that this blog has helped you enhance your knowledge regarding the Custom UI Components. All the widgets are enclosed inside a UI layout and if you would like to learn more about layouts, check out our article on Android UI layouts. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass