android - changing button background color and keep icon (image) when user press on it


Keywords:android 


Question: 

I have like 20 buttons with different icons (images) I need to change the background color of the button when I click (press) and keep the background icon(image)

I need something that doesn't need to make selector for each button because all of the buttons should have the same background colors (normal and selected) with only different icons

I found this concept but using it will need to have selector for each button

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

    <item android:state_pressed="true">
        <layer-list>
            <item>
                <bitmap android:gravity="center" android:src="" android:tileMode="repeat" />
            </item>
            <item>
                <shape>
                     <gradient android:angle="270" android:endColor="#a0e0b071" android:startColor="#a0a67637" />
                     <stroke android:width="1dp" android:color="#5c3708" />
                     <corners android:radius="5dp" />
                     <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
                </shape>
            </item>
        </layer-list>
    </item>

    <item android:state_enabled="true">
        <layer-list>
            <item>
                <bitmap android:gravity="center" android:src="" android:tileMode="repeat" />
            </item>
            <item>
                <shape android:shape="rectangle">
                    <gradient android:angle="270" android:endColor="#a0a67637" android:startColor="#a0e0b071" />
                    <stroke android:width="1dp" android:color="#5c3708" />
                    <corners android:radius="5dp" />
                    <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
                </shape>
            </item>
        </layer-list>
    </item>


</selector>

1 Answer: 

Set the button's tint colour (the android:backgroundTint attribute in XML) to its unselected colour.

Then in the button's onClick method execute this to change tint colour of button to its selected state:

//set the button's background tint colour to its selected state colour button.setBackgroundTintList(ContextCompat.getColorStateList(this, selectedIntColour));