i have 20 imageviews with background image set.
When user clicks on one image and after on a second one, i would like that the two
imageviews can swap their image background.
With the code i built, i got that ONLY the first image clicked updates his background.
private View z; //view for temporary save the first clicked image
public ImageView[] images = new ImageView[20]; //array with my imageviews
public void onClick(View v) {
if (attivo == false) {
attivo = true;
z = v; } //save the clicked view to a temporary one
else {
//we enter here when we click on the second image
//this cycles search inside the array which imageview
//has the same ID of the saved one or the new one (the first/second image clicked)
for (int h = 0; h<20; h++) {
if (images[h].getId()== z.getId()) {
images[h].setBackgroundDrawable(v.getBackground());}
}
for (int h = 0; h<20; h++) {
if (images[h].getId()== v.getId()) {
images[h].setBackgroundDrawable(z.getBackground());}
}
attivo = false;
}
}
The first cycle works! set the second background to the first imageview clicked.
The second cycle, even if the commands are executed, doesn’t work! the background is always the original one.
I know that i could do it in some different ways like use src instead of background, or
gridviews. But please i would like to know why this code doesn’t totally work.
The best solution should be store in two variables your background resources:
And then set your background drawable referencing to that variables:
in one case:
and viceversa: