android: dynamically change FAB(Floating Action Bu

2019-01-22 17:12发布

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

5条回答
混吃等死
2楼-- · 2019-01-22 17:40

Or you use the Support Library:

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
查看更多
贼婆χ
3楼-- · 2019-01-22 17:42

If you are using the Support Library:

floatingActionButton.setImageResource(R.drawable.icon_name)
查看更多
对你真心纯属浪费
4楼-- · 2019-01-22 17:56

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

fab.setImageResource(R.mipmap.ic_arrow_forward);

查看更多
我只想做你的唯一
5楼-- · 2019-01-22 17:56

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));
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-22 18:03

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));
查看更多
登录 后发表回答