Changing Button Color without changing the shape in android
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:
- Create a shape drawable.
- 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.
Here is a solution that worked for me, that contrary to the accepted solution will allow you to change the color dynamically:
myButton = (ImageButton)myView.findViewById(R.id.my_button);
Drawable roundDrawable = getResources().getDrawable(R.drawable.round_button);
roundDrawable.setColorFilter(Color.BLUE, Mode.SRC_ATOP);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myButton.setBackgroundDrawable(roundDrawable);
} else {
myButton.setBackground(roundDrawable);
}
XML of the "round_button" drawable I used, as an example:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#4db6ac"/>
</shape>