Reputation: 37
I want to change the images in image view on Onclick
function. I have already tried this:
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();
}
}
}
});
Upvotes: 0
Views: 2197
Reputation: 355
Try this code, its working for me:-
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);
}
}
});
Upvotes: 0
Reputation: 116
Your equals
expressions always return false, I would expect that none of your if
blocks is executed. Did you debug that code?
I would suggest to keep the state in another variable, e.g. with an enum
.
Additionally you should use setImageDrawable
for performance reasons. See the javadoc of setImageResource
:
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup
Upvotes: 0
Reputation: 10881
bt_audiocapture.getResources().getDrawable(R.drawable.ic_mic)
returns a Drawable
object. You can't compare it to R.drawable.ic_mic
, which is integer
. That is something like comparing a car
to green color
.
To accomplish your task, make some field like private int state = 0;
, and some constants like
private final STATE_PLAYING = 1;
private final STATE_STOPPED = 2;
private final STATE_NONE = 0;
and then:
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;
}
Upvotes: 1