简体   繁体   中英

How to check which image is linked to ImageView in android?

Well i have one button and one ImageView in my app. What i am trying to do is when i pressing on the button then the image at the ImageView will change. All i have are two pics file.

What i am trying to do is - if the first pic is linked to the ImageView than change it to pic2 by clicking on the button, and if pic2 is linked than a click on the button will change it back to the first pic file.

here's the onClick method i tried to use:

public void onClick(View v) {

        ImageView ib1 = (ImageView)findViewById(R.id.imageView1)

         View p1 = findViewById(R.drawable.pic1); 

        if(ib1.getResources()==R.drawable.pic1){
            ib1.setImageResource(R.drawable.pic2); 
        }else{
            ib1.setImageResource(R.drawable.pic1); 
        }

    }

Thanks for any kind of help

Rather than checking the image, I would suggest set the information tag of the ImageView each time you change the image, like:

if(ib1.getTag() != null && ib1.getTag().toString().equals("pic1")){
 ib1.setImageResource(R.drawable.pic2); 
 ib1.setTag("pic2");
} else {
 ib1.setImageResource(R.drawable.pic1); 
 ib1.setTag("pic1");
}
private ImageView ib1;
private int currentImage;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ib1 = (ImageView) findViewById(R.id.imageView1);
    currentImage = R.drawable.pic1;
}

public void onClick(View view){
    currentImage = (currentImage == R.drawable.pic1) ? R.drawable.pic2 : R.drawable.pic1;
    ib1.setImageResource(currentImage);
}

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