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

牧云@^-^@ 提交于 2021-02-05 06:18:05

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/19482272/how-to-check-which-image-is-linked-to-imageview-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!