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.
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.
This worked for me - changing at run-time/ dynamically. For example, when the button is clicked, the colour changes, but it's shape needs to stay the same.
First, you need to define in xml the button:
<Button
android:id="@+id/myButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/buttonshape"
android:text="Change Colour but keep shape, please" />
You will see above it calls buttonshape, so in your drawable folder:
(It's a rectangle, grey, with a dark grey border of 1dp)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#D3D3D3" />
<corners android:radius="3dp" />
<stroke
android:width="1dp"
android:color="#aeaeae" />
</shape>
Now a new xml file in drawable folder, buttonpressed.xml, for the button pressed state. The colour will be green, everything else the same.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
android:shape="rectangle">
<solid android:color="#2AB40E" />
<corners android:radius="3dp" />
<stroke
android:width="1dp"
android:color="#aeaeae" />
</shape>
Now, on button click in our activity:
private void myButton() {
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// keep the slightly rounded shape, when the button is pressed
myButton.setBackgroundResource(R.drawable.buttonpressed);
etc..etc...
It's an old question, but for future seekers, this worked for me...
In drawable the button shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp" />
</shape>
In my layout.xml for the button:
<Button
android:id="@+id/button"
android:layout_width="150dp"
android:layout_height="38dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="@drawable/buttonshape"
android:backgroundTint="@color/colorButtonOrange"
android:text="@string/button_text"
android:textColor="@color/colorWhite"/>
With the android:backgroundTint, the Buttons get an orange Color when the activity is started.
In my Activity, I change the button color with only one line:
button.getBackground().setColorFilter(Color.GREY, PorterDuff.Mode.SRC_ATOP);
I had the same problem when using "setBackgroundColor" was changing the shape of the View. I solved it with "setTint"