Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android studio change background image for multiple images

Tags:

android

image

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);

            }

        }
    });
like image 600
arater 2000 Avatar asked Jan 17 '26 08:01

arater 2000


1 Answers

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);
            }

        }
    });
like image 116
iknow Avatar answered Jan 20 '26 01:01

iknow