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

I am working on an example application in which I need to get the image presentation resource in the onClick listener and compare it with the image source that I know exists. If the resources are the same, I want to start another intention. The problem I'm currently facing is accessing this ImageView (and therefore its Id resource identifier) ​​to compare with the resource that can be retrieved.

@Override
// should int be final ??
public View getView(final int position, View convertView, ViewGroup parent) {

    ImageView imageView;
    if (convertView == null) {  // if it not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) { 
// This is not working and I need to find a way to solve this >>
                if (((ImageView)v).getResources().getInteger(0) == R.drawable.imageToCompare)
                {
                    // do nothing
                }
                else
                {
                    // do something         
                }
+3
source share
3 answers
+3
if(((ImageView)v).getDrawable().getConstantState() == MainActivity.this
                        .getResources().getDrawable(R.drawable.unlock)
                        .getConstantState()))
{

// Do Something
}
+2

- setTag() getTag. , .

public View getView(int position, View convertView, ViewGroup parent) Imageview .

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

Then in onClickyou just compare View vwith your id drawable. For example, I wanted to change the image on click, and I encoded it that way. Pay attention to how I also change the tag when setting a new method

        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);
                } 
            }
        });
+1
source

All Articles