Sunday, January 11, 2015

How to create a round/circle Button in Android

Round or Circle Button
Android app users like the circle button within the app interface. By default android Button widget shape is rectangular. So to show a round or circle button in an android application, the app developer needs to write some custom code to generate it. In this android app development tutorial, we will show how can a developer easily display a round Button in their app.

By two steps of code, we will make a circle Button. At first, in the XML layout file, we will put a background property inside the Button tag. The background property value point to an XML drawable file that actually draws the circle button in the app interface.

XML drawable file selector holds an item that declares the shape of the actual widget. Here we define an oval shape to generate a circle Button. This oval shape has a five-dp width border and a background color. The height and width must be equal, so the button will render as a circle/round button. The following image shows the output of our coding.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8FF">

    <Button
        android:id="@+id/push_button"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:background="@drawable/button_bg_round"
        android:padding="15dp"
        android:text="Circle Button"
        android:elevation="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/drawable/button_bg_round.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!--button pressed state background color-->
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <stroke android:color="#CDEAEE" android:width="3dp" />
            <solid android:color="#87CEEB"/>
            <size android:width="150dp" android:height="150dp"/>
        </shape>
    </item>

    <!--button default background color-->
    <item>
        <shape android:shape="oval">
            <stroke android:color="#1E90FF" android:width="3dp" />
            <solid android:color="#87CEEB"/>
            <size android:width="150dp" android:height="150dp"/>
        </shape>
    </item>
</selector>