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);
}
}
});
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With