代码之家  ›  专栏  ›  技术社区  ›  Bisma Frühling

单击浮动操作按钮图标时切换该图标

  •  4
  • Bisma Frühling  · 技术社区  · 7 年前

    我有两张可绘制的图片,最初FAB设置为R.drawable。图标1,我想把它设置为R.drawable。单击图标2,再次单击时将其设置回图标1,依此类推。。。

    2 回复  |  直到 7 年前
        1
  •  11
  •   Chirag    7 年前

    希望这有帮助,我们有一个布尔值 flag 这表示当前在晶圆厂中可见的图标。

    FloatingActionButton fab;
    boolean flag = true; // true if first icon is visible, false if second one is visible.
    
    fab = (FloatingActionButton) findViewById(R.id.fab);
    
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                if(flag){
    
                    fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon2));
                    flag = false;
    
                }else if(!flag){
    
                    fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon1));
                    flag = true;
    
                }
    
            }
        });
    
        2
  •  0
  •   Codelaby    2 年前

    fun FloatingActionButton.icon(@DrawableRes id: Int = 0) {
        setImageResource(id)
    }
    
    fun FloatingActionButton.backgroundColor(@ColorRes colorRes: Int = 0) {
        backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
    }
    
    fun FloatingActionButton.iconColor(@ColorRes colorRes: Int = 0) {
        imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
    }
    

    示例:

    var flag = true
    
    binding.fabToggleService.setOnClickListener {
        flag = !flag
    
        if (flag) {
            binding.fabToggleService.apply {
                icon(R.drawable.ic_round_stop_24)
                iconColor(R.color.white)
                backgroundColor(R.color.md_red_400)
    
        } else {
            binding.fabToggleService.apply {
                icon(R.drawable.ic_round_play_arrow_24)
                iconColor(R.color.white)
                backgroundColor(R.color.md_blue_400)
        }
    
    }