简体   繁体   中英

How to change image of a button on click?

I have an array of bitmaps ArrayList<Bitmap> images = new ArrayList<>(3) and need to change the image of a ImageButton in every click, first images(0) then, after I click image(1) and finally image(2) .

For this I am using myImageButton.setImageBitmap(images.get(0)) for the first image, how do I change to the next and then to the third?

You should use

int currentPos = 0;
onclick(){
 currentPos = (currentPos+1)%(images.size()-1)
 myImageButton.setImageBitmap(images.get(currentPos))
}

You can use

int currentPos = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        myImageButton.setImageBitmap(images.get(0))
}


@Override
public void onClick(View v){
    currentPos++;
    if(currentPos == 2){
        // if the imagebutton has the bitmap from position 2, you can do what you want
        //example:
        currentPos = 0;// so you have the first Bitmap you had when the user didn't click on the ImageButton
    }
    myImageButton.setImageBitmap(images.get(currentPos));
}

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