Change the color of a Button that already has an assigned Background

Asked

Viewed 785 times

2

Hello, in my application there is a table (Alert Dialog) that will be used to select the color of a component. In this table there are several equal buttons with the background already set so that they stay with a round style. For this I used an XML file with the property Shape.

I wanted each of these buttons to have a different color. However, I don’t want to create multiple XML files defining each one’s color. I want to know if you have any different way to change the color without touching your background, or even changing the color of Shape button.

I also accept suggestions to make this table in a different way, without using a lot of buttons.

XML file for button background:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"
        />

    <stroke
        android:width="2dp"
        android:color="@color/colorPrimary" />
</shape>

1 answer

2


If minSdkVersion >= 21 use

android:backgroundTint

For lower versions, change the color of the solid for #FFFFFF and use the following code to put the color you want,

button = (Button)findViewById(R.id.button);
Drawable background = button.getBackground();
background.setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY); 

If you want an alternative to a layout "full of buttons" see this reply. It uses a Spinner to choose the color, but the same Adapter can be used in a Listview.

  • The second option worked perfectly for me, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.