William Macleod William Macleod - 4 months ago 71
Android Question

Change FAB background color when disabled

I'm trying to figure out how I can change the background color of the floating action button when it is disabled for a duration of 2 seconds after being pressed. I would also like it to return to its original color when the 2 second duration is over.

This is the code for the 2 second delay when pressed. This code is in a fragment within the MainActivity.

appBar.setExpanded(true, true);
fab.setVisibility(View.VISIBLE);
fab.setImageResource(R.drawable.ic_phone_white_18dp);

fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fab.setClickable(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
fab.setClickable(true);
}
});
}
}, 2000);


I've tried playing around with the
StateListDrawable
methods in the documentation but have not come across anything that works.

This is the XML for the color themes of the FAB

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/themeColorPressed" android:state_pressed="true"/>
<item android:color="@color/themeColorPressed" android:state_checked="true"/>
<item android:color="@color/themeColorPressed" android:state_selected="true"/>
<item android:color="@color/themeColorPressed" android:state_enabled="false"/>
<item android:color="@color/themeColor" android:state_enabled="true"/>
</selector>

Answer

Just call fab.setBackgroundColor(Color.GRAY); (or whatever color) when you disable it. Also you can use fab.setBackgroundColor(getResources().getColor(R.color.colorAccent0)); to use a resource color.

Comments