Reputation:
I'm trying to make an ImageView button toggle when I click on it. I've got the below code:
ImageView button01 = (ImageView) findViewById(R.id.button01);
button01.setOnClickListener(new OnClickListener() {
int button01pos = 0;
public void onClick(View v) {
if (button01pos == 0) {
button01.setImageResource(R.drawable.image01);
button01pos = 1;
} else if (button01pos == 1) {
button01.setImageResource(R.drawable.image02);
button01pos = 0;
}
}
});
But for some reason button01 is underlined in red in Eclipse and it gives the error:
Cannot refer to a non-final variable button01 inside an inner class defined in a different method
Does anyone know why it's doing this and how to fix it?
Thanks
Upvotes: 2
Views: 8831
Reputation: 1
Try this, it worked for me. Here checkbox visibility is set to "Invisible"...! this code is inside a button OnClickListener...!
@Override
public void onClick(View v) {
ImageView iv_icon = (ImageView) findViewById(R.id.icon);
CheckBox cb = (CheckBox) findViewById(R.id.cb);
if (cb.isChecked()) {
iv_icon.setImageResource(R.drawable.image01);
cb.setChecked(false);
} else if (!cb.isChecked()) {
iv_icon.setImageResource(R.drawable.image02);
cb.setChecked(true);
} else {
// Nothing happens
}
}
Upvotes: 0
Reputation: 409
Try this,
int button01pos = 0;
ImageView button01 = (ImageView) findViewById(R.id.button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (button01pos == 0) {
button01.setImageResource(R.drawable.image01);
button01pos = 1;
} else if (button01pos == 1) {
button01.setImageResource(R.drawable.image02);
button01pos = 0;
}
}
});
Upvotes: 0
Reputation:
Here is the working code:
final ImageView button01 = (ImageView) findViewById(R.id.button01);
button01.setOnClickListener(new OnClickListener() {
int button01pos = 0;
public void onClick(View v) {
if (button01pos == 0) {
button01.setImageResource(R.drawable.image01);
button01pos = 1;
} else if (button01pos == 1) {
button01.setImageResource(R.drawable.image02);
button01pos = 0;
}
}
});
Upvotes: 7