Change oval shaped button background programmatically

1.5k views Asked by At

I want to change Button background color programmatically the button shape(oval). I have changed in xml.

This is the code:

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="20dp"/>  
        <solid android:color="#f9f9f9"/>  
        <stroke
            android:width="2dp" android:color="#FFFF4917" /> 
            </shape>

I am using Button.backgroundColor(COLOR.RED) to change this Button but problem is that it's changing button color, but it is making my button rectangular shape(default shape of a button)

2

There are 2 answers

1
SamHoque On BEST ANSWER

You could modify it using this simple method down below

GradientDrawable BackgroundShape = (GradientDrawable)btn.getBackground();
BackgroundShape.setColor(Color.BLACK);
1
AGM Tazim On

Use it. It will make your rectangular shap to oval shap when click on button.

style_login_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="oval">
            <solid android:color="@color/colorDeepOrange"/>
            <size android:width="120dp" android:height="120dp"/>
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="oval">
            <solid android:color="@color/colorOrange"/>
            <size android:width="120dp" android:height="120dp"/>
        </shape>
    </item>
    <item >
        <shape android:shape="oval">
            <solid android:color="@color/colorOrange"/>
            <size android:width="120dp" android:height="120dp"/>
        </shape>
    </item>
</selector>

And apply to Button . Like -

<Button
               android:id="@+id/btnSignin"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="@string/text_btn_login"
               android:textColor="@color/colorWhite"
               android:textSize="25dp"
               android:padding="30dp"
               android:textAllCaps="false"
               android:layout_marginTop="20dp"
               android:layout_marginBottom="20dp"
               android:background="@drawable/style_login_button"/>