You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Activity中获取并切换FloatingActionButton前景的mipmap

问题:FAB切换前景mipmap时,Drawable相等判断失效

我给FloatingActionButton设置了mipmap作为前景,想要每次点击切换前景图,但获取当前mipmap进行条件判断的逻辑始终不生效——设置新图的方法是有效的,但判断部分永远匹配不上。

布局代码:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/selection_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    android:clickable="true"
    android:layout_marginTop="228dp"
    android:layout_marginEnd="24dp"
    android:foreground="@mipmap/im_check_green_white"
    android:backgroundTint="@color/white"
    android:visibility="visible"
    android:contentDescription="@string/selection_fab"/>

失效的Activity代码:

private void setupSelectionFab() {
    
    Drawable fgCur = selectionFab.getForeground().getCurrent();
    Drawable fgGreen = AppCompatResources.getDrawable(this, R.mipmap.im_check_green_white);
    Drawable fgGrey = AppCompatResources.getDrawable(this, R.mipmap.im_check_grey_white);

    if (fgCur.equals(fgGreen)) {
            Log.e(getClass().getSimpleName(), "inside condition 1");
            selectionFab.setForeground(AppCompatResources.getDrawable(this,R.mipmap.im_check_grey_white));
        } else if (fgCur.equals(fgGrey)) {
            Log.e(getClass().getSimpleName(), "inside condition 2");
            selectionFab.setForeground(AppCompatResources.getDrawable(this,R.mipmap.im_check_green_white));
        }
    }
}

原因分析

AppCompatResources.getDrawable()每次调用都会生成新的Drawable实例,哪怕是同一个资源ID。所以用equals()比较两个Drawable对象时,本质是比较对象引用,永远不会相等,导致判断逻辑失效。另外,Android没有直接提供从Drawable实例获取对应资源ID的API,没法通过Drawable反向拿到ID来判断。


解决方案:用状态变量跟踪当前前景图

不要直接比较Drawable对象,而是用一个变量记录当前的状态,比如布尔值或者枚举,根据状态来切换前景图。

修改后的代码示例:

  1. 在Activity里定义状态变量:
// 初始值设为true,因为布局默认是绿色图标
private boolean isGreenChecked = true;
  1. 修改切换逻辑:
private void setupSelectionFab() {
    // 根据当前状态切换图标
    if (isGreenChecked) {
        // 切换为灰色图标
        selectionFab.setForeground(AppCompatResources.getDrawable(this, R.mipmap.im_check_grey_white));
        isGreenChecked = false;
    } else {
        // 切换为绿色图标
        selectionFab.setForeground(AppCompatResources.getDrawable(this, R.mipmap.im_check_green_white));
        isGreenChecked = true;
    }
}
  1. 给FAB绑定点击事件(在onCreate中初始化):
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout);
    
    selectionFab = findViewById(R.id.selection_fab);
    selectionFab.setOnClickListener(v -> setupSelectionFab());
}

内容的提问来源于stack exchange,提问作者Oxorion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:45:41