Search code examples
androidandroid-imageview

getImageResource() Android. Is this possible?


I have set an image for an ImageView using the setImageResource(R.drawable.icon1).

Now my requirement is to find out what is the image that is set for an ImageView and do some processing.

Like

if (imageView.getImageResource() == R.drawable.icon1) {
  //do some processing
else if (imageView.getImageResource() == R.drawable.icon2) {
  //do somethign else
else 
 //display

So I would like to know if there exists a method(AFAIK, it doesn't) and if it doesn't how to keep a track of what resources have been set for an ImageView.

Thanks. Sana.


Solution

  • You're assuming that because you put an integer in, you are able to get an integer back out, and that's not how setImageResource() works. See ImageView#setImageResource(). This is just a convenience method for you: what Android is doing behind the scenes, is looking up the Drawable resource (in most cases, it's a BitmapDrawable, but it could be any type), and then applying that resource to the ImageView as a Bitmap object (i.e., image data only -- it does not have any idea what its original "resource id" was previously).

    Your best solution is going to be keeping track of the last resource id you used:

    imageView.setImageResource(R.drawable.image1);
    this.mLastResourceId = R.drawable.image1;
    // ...
    
    // Later, when checking the resource:
    if (this.mLastResourceId == R.drawable.image1) {
        // Do something
    }