android: dynamically change FAB(Floating Action Button) icon from code

AndroidMaterial DesignFloating Action-Button

Android Problem Overview


How to change FAB icon in an Activity during runtime. I have this code ->

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabMainActivity);

I know this is possible using fab.setBackgroundDrawable(); but i am a newbie to android, don't understand how to do this.

Any help will be highly appreciated.

Thanks

Android Solutions


Solution 1 - Android

Changing FloatingActionButton source:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad, context.getTheme()));
        } else {
            floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad));
    }

This can be replaced by following code from the support library instead:

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));

Solution 2 - Android

If you are using the Support Library:

floatingActionButton.setImageResource(R.drawable.icon_name)

Solution 3 - Android

Or you use the Support Library:

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));

Solution 4 - Android

Assume that you will use the image ic_arrow_forward.png as your fab's background:

fab.setImageResource(R.mipmap.ic_arrow_forward);

Solution 5 - Android

What I am using as follows,

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_btn);

// State 1 -on

fab.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.fab_on));

// State  2 - off

fab.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.fab_off));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHirdesh VishwdewaView Question on Stackoverflow
Solution 1 - AndroidSunnyView Answer on Stackoverflow
Solution 2 - AndroidPaulTView Answer on Stackoverflow
Solution 3 - AndroidPaul SpiesbergerView Answer on Stackoverflow
Solution 4 - AndroidEckoTanView Answer on Stackoverflow
Solution 5 - AndroidUmandaView Answer on Stackoverflow