How to check which image is set in imageview android

北慕城南 提交于 2021-02-20 04:13:07

问题


I have a star image in action bar. When I click on it, then the image should change to ON star. This is working fine. But how to know whether image is at ON state or OFF state.I want something that, if the image is at OFF mode and user taps on ON star, then it should set to ON star image. Initially, the image is set to OFF mode. So for this, I've wrote give line to turn on as user tap on it :

v.setBackgroundResource(android.R.drawable.star_big_on);

Guys pls suggest me for OFF mode if star image is already on. I am not getting any idea.


回答1:


you can check it easily by setting tag of each image or by comparing there resource comparision of resource method is shown below:

if (regProfile.getDrawable().getConstantState() == 
    getResources().getDrawable(R.drawable.ivpic).getConstantState()){             
      Toast.makeText(_con, "Image is ivPic", Toast.LENGTH_LONG).show(); 
} else{
      Toast.makeText(_con, "Image isn't ivPic", Toast.LENGTH_LONG).show(); 
}



回答2:


If my guess is correct you can achieve the functionality like this.change this code accordingly for image onclick

 private Button button;
 public static boolean isclick=false;
 button.setOnClickListener(seathtlistner);
 private View.OnClickListener seathtlistner = new View.OnClickListener() {
 public void onClick(View v) {
// TODO Auto-generated method stub
  if(isclick){
  button.setBackgroundResource(R.drawable.onstarimage);
}else{
  button.setBackgroundResource(R.drawable.offstarimage);
}
isclick=!isclick;
 }



回答3:


You can use Tag property.

img_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Boolean tag_isOn = (Boolean) v.getTag();

                tag_isOn = !tag_isOn;
                v.setBackgroundResource(tag_isOn ?android.R.drawable.star_big_on:android.R.drawable.star_big_off);


                v.setTag(tag_isOn);

            }
        }); 



回答4:


if (img_like.getTag() != null && img_like.getTag().toString().equals("red")) {
                        img_like.setImageResource(R.drawable.heart);
                        img_like.setTag("heart");
                    } else {
                        img_like.setImageResource(R.drawable.red);
                        img_like.setTag("red");
                    }`enter code here`


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

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