John Victor John Victor - 12 days ago 7
Android Question

Changing Button Color without changing the shape in android

When i say

button.setBackgroundColor(Color.BLUE);


the button shape changes to rectangle from default shape. I want to change the button color without affecting its original shape. Please help me.

Answer

Whenever you change the default background of your button the shape is going to change as the default shape is rectangle and the default background is a shape drawable with rounded corners. If you use any other background this rounded corner effect is lost.

You can achieve the same effect with any color or shape if you use a shape drawable as the background.
Here is how you can achieve this:

  1. Create a shape drawable.
  2. Use this drawable as the button's background.


sample code for shape drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid
        android:color="#f8f8f8"/>
    <corners
        android:radius="4dp"/>
    <padding 
        android:left="10dp"
        android:right="10dp"
        android:top="5dp"
        android:bottom="5dp"/>
    <stroke 
        android:width="1dp"
        android:color="#aeaeae"/>
</shape>


If you want to have a button with a selector then use this xml as the background

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true">
        <shape >
            <solid
                android:color="#ff0000" />
            <stroke 
                android:width="1dp"
                android:color="#ff0000" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item >
        <shape >
            <gradient
                android:startColor="#ff2727"
                android:endColor="#890000"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#620000" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>        
    </item>
</selector>

This is a selector xml with items as the different shape drawables. If the button is pressed that is the button's state is state_pressed then the top shape drawable is used else the bottom shape drawable is used.
I hope this will help.

Comments