Android: How to compare resource of an image with R.drawable.imagename?

∥☆過路亽.° 提交于 2019-12-04 14:34:34
Michael

You can't get a drawable id from an ImageView. But if you set it from code, you can also store it somewhere, for example in the tag field. Take a look at the similar question: Who I compare an background Image resource TextView with a R.drawable.bg_image for switch.

if(((ImageView)v).getDrawable().getConstantState() == MainActivity.this
                        .getResources().getDrawable(R.drawable.unlock)
                        .getConstantState()))
{

// Do Something
}

The proper way is to user setTag() and getTag. I guess you are making your own adapter.

In the method public View getView(int position, View convertView, ViewGroup parent), you set tag to Imageview when you add other properties to it.

ImageView temp = (ImageView) v.findViewById(resId);
temp.setImageResource(icon);
temp.setTag(icon); //drawable unique ID will be my identifier here

Then in the onClick you simply compare View v with your drawable id. For example, I wanted to change image on click and I coded it this way. Take notice how I also change tag when I set a new drawable

        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if ((Integer)v.getTag() == R.drawable.current_img) {
                    v.setBackgroundResource(R.drawable.new_img);
                    v.setTag(R.drawable.new_img);
                } 
            }
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!