57

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

Hirdesh Vishwdewa
  • 2,334
  • 1
  • 19
  • 33

5 Answers5

101

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));
Jithin Sunny
  • 3,352
  • 4
  • 26
  • 42
  • 1
    Try to avoid `getApplicationContext` as much as possible – zozelfelfo Oct 15 '15 at 06:30
  • @zozelfelfo why is that? – SaKet Jan 27 '16 at 18:31
  • 7
    That's not necessarily true. It depends on what you are trying to accomplish. Activity context can cause memory leaks depending on how you are using it. Typically it's the activity context that is troublesome because it can cause memory leaks. If the activity dies and another object has a reference to that activity via the context it can't be garbage collected. However, there are some cases when you want to use the activity context over the app context, [ex](http://developer.android.com/reference/android/content/ContextWrapper.html#getApplicationContext%28%29). – sam_c Feb 08 '16 at 21:14
  • 1
    How can I set an icon to an Extended FAB programmatically? – Mark Delphi May 07 '20 at 10:19
21

If you are using the Support Library:

floatingActionButton.setImageResource(R.drawable.icon_name)
PaulT
  • 4,266
  • 2
  • 13
  • 15
18

Or you use the Support Library:

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
Paul Spiesberger
  • 5,630
  • 1
  • 43
  • 53
2

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

fab.setImageResource(R.mipmap.ic_arrow_forward);
hata
  • 11,633
  • 6
  • 46
  • 69
EckoTan
  • 111
  • 1
  • 2
  • If you use R.drawable.* or R.mipmap.*, using `setImageResource` is far more straight forward. I think this answer is the best. – hata Oct 15 '21 at 08:01
1

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));
Umanda
  • 4,737
  • 3
  • 23
  • 28