android:从代码中动态更改FAB(浮动操作按钮)图标

ezc*_*odr 41 android material-design floating-action-button

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

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabMainActivity);
Run Code Online (Sandbox Code Playgroud)

我知道这是可能的使用,fab.setBackgroundDrawable();但我是Android的新手,不明白该怎么做.

任何帮助将受到高度赞赏.

谢谢

Sun*_*nny 78

更改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));
    }
Run Code Online (Sandbox Code Playgroud)

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

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
Run Code Online (Sandbox Code Playgroud)

  • 这不一定是真的.这取决于你想要完成什么.活动上下文可能会导致内存泄漏,具体取决于您使用它的方式.通常,它是活动上下文很麻烦,因为它可能导致内存泄漏.如果活动死亡而另一个对象通过上下文引用该活动,则无法进行垃圾回收.但是,在某些情况下,您希望在应用程序上下文中使用活动上下文,[ex](http://developer.android.com/reference/android/content/ContextWrapper.html#getApplicationContext%28%29). (6认同)

Spi*_*pau 17

或者您使用支持库:

floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad));
Run Code Online (Sandbox Code Playgroud)


Pau*_*ulT 13

如果您使用的是支持库:

floatingActionButton.setImageResource(R.drawable.icon_name)
Run Code Online (Sandbox Code Playgroud)