0

如何通过检查当前图像文件来更改 Button 的背景图像。假设我想通过检查当前打开的图像来尝试打开/关闭声音的图像。

主要的.xml

<Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:onClick="onClickSound"
        android:background="@drawable/sound11"
        android:onClick="onClickSound" />

main.java

public void onClickSound(View view) {
    final Button btn1 = (Button) findViewById(R.id.button3);

    Drawable i = btn1.getBackground();

            /*How to check which image resource is set*/

    btn1.setBackgroundResource(R.drawable.sound00);
}

任何人都可以帮助检查它。我试过了,但我无法将 R.drawable.sound00 与“i”进行比较。

4

1 回答 1

2

您可以尝试使用标志来显示图像的最后状态并根据该状态更新内容。这是一种更好的方法来确定图像文件本身以外的其他方面的状态。基本上,这可以尝试:

        boolean isPlayingSound = false; 
        public void onClickSound(View view) {
             //update this variable accordingly
             isPlayingSound = !isPlayingSound
             view.setBackgroundResource(isPlayingSound ? R.drawable.sound11 : R.drawable.sound00);          
        }
于 2013-05-20T10:46:57.223 回答