How to get id from an ImageView in android?

0

How do I get an id of an image from an ImageView. Example, for me to set an image in my ImageView I use the following code.

  

imageView.setImageResource (R.drawable.icone_x);

How do I reverse the process? For example, I want to get an integer that references R.drawable.icone_x, I wanted more or less that.

  

int resID = imageView.getImageResource ();

But there is no such method.

    
asked by anonymous 27.10.2014 / 20:12

2 answers

1

The @PauloRodrigues answer is pretty cool. But I leave my suggestion, which would be to extend ImageView , adding the behavior you want. Of course, it involves refactoring if you are already using ImageView's in your application, but do not involve adding more code (which you can forget) by setting tag to ImageView . >

The subclass would be:

public class CustomImageView extends ImageView {

    private int mImageResource;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs, 0, defStyle);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        // Recupera o id do resource setado no xml
        final TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ImageView, defStyleAttr, defStyle);
        mImageResource = a.getResourceId(com.android.internal.R.styleable.ImageView_src, 0);

        a.recycle();
    }

    @Override
    public void setImageResource(int resId) {
        mImageResource = resId;
        super.setImageResource(resId);
    }

    public int getImageResource() {
        return mImageResource;
    }
}

The use in xml would be similar to the others, just changing ImageView by nome.do.seu.pacote.CustomImageView .

    
27.10.2014 / 23:43
2

I'm assuming your intent is to get an integer referencing your image, but that's not what really happens when you use the setImageResource method. You can check out ImageView#setImageResource() than the Android does behind, which is to get a resource that in most cases is a BitmapDrawable , but can be another type, and then it is applied to ImageView .

The best solution for your case I believe it is to save the name or the ID itself somewhere to later retrieve, for example using setTag() :

imageView.setImageResource(R.drawable.image1);
imageView.setTag("image1");

And then you can recover it like this:

int resId = getResources().getIdentifier(imageView.getTag(), "drawable", getPackageName());

Of course, it's an assumption that depends on how you want to deploy.

    
27.10.2014 / 23:04