How to Create Custom Button in Android

If you want to add a button with unique features that are not provided by default android button, one of the options to solve this issue is to create a custom button in android.

You can create a custom button either by extending android View class or extending android Button class.

We are not going to create a sample custom button but rather we will illustrate the necessary code you will need in creating a custom button in android.

CustomButton.java

Go to your project package folder and create a new java class.

Name the class CustomButtonor any name of your choice.

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatButton;

public class CustomButton extends AppCompatButton {

    private static final String TAG = CustomButton.class.getSimpleName();

    private Context context;


    public CustomButton(Context context) {
        super(context);
    }


    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private void init(Context context){
        this.context = context;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

}

In the code above, the CustomButtonclass extends from android button. The following there constructors and onDraw()method were overridden.

Depending on the features of the custom button will determine the nature of code you will add in the skeleton code structure above.

Below is how to add the CustomButtonto the XML layout file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <com.inducesmile.buttonsnippets.CustomButton
        android:id="@+id/custom_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorWhite"
        android:text="Custom Button"
        android:background="@color/colorPrimaryDark"/>

</androidx.appcompat.widget.LinearLayoutCompat>

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment