Android Rounded Corners Button with Background Color

Content:
1) How to create a rounded corners Button in Android
2) How to set Button pressed state background color in Android when clicked

1.Create a xml file in your drawable folder like rounded_corner_background.xml and paste the following markup:

rounded_corner_background.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="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CC9933" android:endColor="#CC9933"  />
        </shape>
    </item>

<!--button focused state background color-->
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CCCC33" android:endColor="#CCCC33"  />
        </shape>
    </item>

 <!--button default background color-->
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CCCCCC" android:endColor="#CCCCCC" />
        </shape>
    </item>
</selector>

Button Default Background Color

button focused state background color

button pressed state background color


2. Now use this drawable for the background of your Button.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:padding="30dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner_background"
        android:text="Rounded Corners Button !"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

No comments:

Post a Comment

Popular Posts