代码之家  ›  专栏  ›  技术社区  ›  user7854507

如何在按下按钮时动态向按钮添加图像

  •  -1
  • user7854507  · 技术社区  · 6 年前
    case R.id.btn_sound:
            if (sp.getBoolean("mute", false)) {
                ed.putBoolean("mute", false);
                mp.setVolume(0.2f, 0.2f);
                ((Button) findViewById(R.id.btn_sound)).setText(getString(R.string.btn_mute));
            } else {
                ed.putBoolean("mute", true);
                mp.setVolume(0, 0);
                ((Button) findViewById(R.id.btn_sound)).setText(getString(R.string.btn_sound));
            }
            ed.commit();
    break;
    

    而不是文本

    setText(getString(R.string.btn_声音))

    我想在点击按钮时显示图像

    2 回复  |  直到 6 年前
        1
  •  1
  •   AmirMohammad Gholami    6 年前
    1. 使用按钮并使用以下方法将图像设置为背景资源: Button.setBackgroundResource(yourResID)

    2. 使用ImageButton并使用以下方法将图像设置为ImageResource: ImageButton.setImageResource(yourResID)

    注意:如果你想在按钮中同时保留文本和图像,你甚至可以在文本旁边的按钮上使用right或left drawable。

        2
  •  1
  •   Alexei Artsimovich    6 年前

    试试setBackground()方法。或者使用ImageButton,然后可以使用setImageResource()方法。