我想在Onclick
功能的图像视图中更改图像。我已经尝试过了:
bt_audiocapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (checkPermission()) {
if (bt_audiocapture.getResources().getDrawable(R.drawable.ic_mic).equals(R.drawable.ic_mic)) {
start();
bt_audiocapture.setImageResource(R.drawable.ic_stop);
} else if (bt_audiocapture.getResources().getDrawable(R.drawable.ic_stop).equals(R.drawable.ic_stop)) {
stop();
bt_audiocapture.setImageResource(R.drawable.ic_play);
} else if (bt_audiocapture.getResources().getDrawable(R.drawable.ic_play).equals(R.drawable.ic_play)) {
play();
}
}
}
});
答案 0 :(得分:1)
bt_audiocapture.getResources().getDrawable(R.drawable.ic_mic)
会返回Drawable
个对象。您无法将其与R.drawable.ic_mic
进行比较,即integer
。这类似于将car
与green color
进行比较。
要完成任务,请创建一些字段,如private int state = 0;
,以及一些常量,如
private final STATE_PLAYING = 1;
private final STATE_STOPPED = 2;
private final STATE_NONE = 0;
然后:
if (state == STATE_NONE) {
start();
bt_audiocapture.setImageResource(R.drawable.ic_stop);
state = STATE_PLAYING;
} else if (state == STATE_PLAYING) {
stop();
bt_audiocapture.setImageResource(R.drawable.ic_play);
state = STATE_STOPPED;
} else if (state == STOPPED) {
play();
state = STATE_PLAYING;
}
答案 1 :(得分:0)
您的equals
表达式总是返回false,我希望您的if
块都不会被执行。你调试了那段代码吗?
我建议将状态保存在另一个变量中,例如使用enum
。
此外,出于性能原因,您应该使用setImageDrawable
。请参阅setImageResource
的javadoc:
这会在UI线程上进行Bitmap读取和解码,这会导致延迟打嗝
答案 2 :(得分:0)
试试这段代码,它适合我: -
img = (ImageView) findViewById(R.id.img);
img.setTag(0);
img.setImageResource(R.drawable.images);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Integer.parseInt(img.getTag().toString()) == 0) {
img.setImageResource(R.drawable.cam);
img.setTag(1);
} else {
img.setImageResource(R.drawable.images);
img.setTag(0);
}
}
});