Reputation: 143
I have 5 images in the drawable folder (bg1, bg2, bg3, bg4, bg5), bg1 is my default background.
I want to change the the image of the background in order eatch time I click the button and when it arrive to the final image it should go again to the first image,
for example if I cliked the button it should set bg2 as background and if I clicked it again it should set bg3 as background and so on,
I tried the below code but it only change the background image one time.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int x = 0;
while(x < 5){
x ++;
// Give image name that you want to show on button click
layout.setBackgroundResource(R.drawable.bg+x);
}
}
});
Upvotes: 3
Views: 1074
Reputation: 9912
You have to set x
as a global variable. You set x
in function so it is always 0
.
int x = 0; //global variable in activity/fragment
...
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
x ++;
x %= 5;
if (x==0) layout.setBackgroundResource(R.drawable.bg1);
else if (x==1) layout.setBackgroundResource(R.drawable.bg2);
else if (x==2) layout.setBackgroundResource(R.drawable.bg3);
else if (x==3) layout.setBackgroundResource(R.drawable.bg4);
else layout.setBackgroundResource(R.drawable.bg5);
}
}
});
Upvotes: 3
Reputation: 36423
Try:
// declare the varibale globally, or else everytime the onClick is called it will be reset to 0
int x = 1;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int bg = 0;
// are we larger than 5? lets start again at 1 :)
if (x == 6) x = 1;
if (x == 1) bg = R.drawable.bg1;
if (x == 2) bg = R.drawable.bg2;
if (x == 3) bg = R.drawable.bg3;
if (x == 4) bg = R.drawable.bg4;
if (x == 5) bg = R.drawable.bg5;
layout.setBackgroundResource(bg);
// lets increment you for the next round
x++;
}
}
});
Upvotes: 2