android: 从代码中动态更改 FAB(Floating Action Button) 图标

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

如何在运行时更改 Activity 中的 FAB 图标。我有这个代码 ->

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

我知道使用 fab.setBackgroundDrawable(); 是可行的,但我是 android 的新手,不知道如何操作。

非常感谢任何帮助。

谢谢

更改 FloatingActionButton 来源:

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));
    }

这可以替换为支持库中的以下代码:

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

或者您使用支持库:

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

如果您使用的是支持库:

floatingActionButton.setImageResource(R.drawable.icon_name)

我使用的如下,

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));

假设您将使用图像 ic_arrow_forward.png 作为 fab 的背景:

fab.setImageResource(R.mipmap.ic_arrow_forward);