In my application, I have button and ImageView
.
Here when i press button i want to change ImageView
. I have 5 images in my drawable folder. On press button ImageView changes images one by one based on button click. I want it's solution.
Grateful to anyone that can help.
Maintain an array of image ids and inside onClick, set images using id from the array, then increment index.
Eg:-
ArrayList<Integer> ids=new ArrayList<Integer>();
ids.add(R.drawable.image1);
ids.add(R.drawable.image2);
ids.add(R.drawable.image3);
ids.add(R.drawable.image4);
ids.add(R.drawable.image5);
Int index=0
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(index<ids.size()){
imageview.setImageResource(ids.get(index));
index++;
}
else index=0;
}
});
As @Nizam said just maintain an array of id and load dinamically the image in the onClick(). Instead of the Random use a field variable and increment it. Be careful to the array length!
final int[] ids = new int[] { R.drawable.img1, R.drawable.img2 };
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int randomId = new Random().nextInt(ids.length);
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setImageDrawable(getResources().getDrawable(randomId));
}
});
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