简体   繁体   中英

Button click event to change image

Is there any method available for suppose if I click the button than the image should be change. Number of times I click the button the image should be change.

I suppose you want to change the image of an ImageView

For changing the image of an ImageView , inside the onClick() of the Button use:

myImageView.setBackgroundResource(R.drawable.my_image_name);

Here, myImageView is the object bound an ImageView , and
R.drawable.my_image_name is the location of the image file present in your Drawable folder.

For more details refer to this thread

Update

I have use a random number and switch case. When I click the button the number will be generated and pass to switch case and based on that the image should appear in the image view.

In that case, let's assume you have 3 images in your drawable folder.
You can use a HashMap where the key is the index and the value is the image-path

HashMap<Integer, Integer> imageMap=new HashMap<Integer, Integer>();
imageMap.put(1,R.drawable.my_image4);
imageMap.put(2,R.drawable.my_image3);
imageMap.put(3,R.drawable.my_image2);

Now, generate Random number in range 1-3

int min = 1;
int max = 3;
int randomNumber = new Random().nextInt((max - min) + 1) + min;

Finally, set the image at the randomly generated position.

int randomImageId = imageMap.get(randomNumber);
myImageView.setBackgroundResource(randomImageId);

Hope this helps

button.setOnClickListener(v -> {
   button.setBackgroundResource(R.drawable.image);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM