如何在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对象,而是用一个变量记录当前的状态,比如布尔值或者枚举,根据状态来切换前景图。
修改后的代码示例:
- 在Activity里定义状态变量:
// 初始值设为true,因为布局默认是绿色图标 private boolean isGreenChecked = true;
- 修改切换逻辑:
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; } }
- 给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
相关产品推荐
相关产品推荐

