4

I need to quickly and safely check if an android.widget.ImageView currently has a Bitmap of non zero value attached. What is a quick way to do this.

Update my image view is set initially drawable set to "logo.png" so if I know that it is currently set to logo.png than I know that the bitmap has not yet been set. So how can I check if background drawable is currently logo.png

Thanks

NextDroid
  • 337
  • 2
  • 4
  • 10

4 Answers4

12

Use getDrawable() method, if it return null then nothing assigned

if( mImageView.getDrawable() != null){

  //Image Assigned

}else{
  //nothing assigned

}
Siv
  • 1,026
  • 19
  • 29
Changdeo Jadhav
  • 706
  • 9
  • 23
  • In the queston, he mentioned the imageview is already attached with default "logo.png". If you use your method. It will not return null. since "logo.png" is there already!! – Anees Deen Oct 28 '14 at 10:28
  • I have another situation here, where I have a background color set. The same, getDrawable does not return null even though no src is set. – Oliver Hausler Jan 19 '15 at 19:36
1

Assign ImageView to variable in onCreate:

someImage = (ImageView) findViewById(R.id.imageView);

Then a simple if-else statement:

Bitmap bm = ((BitmapDrawable) someImage.getDrawable()).getBitmap();

                boolean hasDrawable = (bm != null);
                if(hasDrawable) 
                {
                    hasImage();
                }
                else 
                {
                    Toast.makeText(AppSettings.this, "No Bitmap", Toast.LENGTH_SHORT).show();
                }
Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
1

Kotlin Extension Solution:

Add this to simplify checks and make it more readable

fun ImageView.hasDrawable() = drawable != null

and then call

myView.hasDrawable()
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Gibolt
  • 42,564
  • 15
  • 187
  • 127
0

Get Bitmap attached to ImageView

Check this out.

It looks like you have to create a bitmap from the ImageView and check to see if it is null.

imageView.setDrawingCacheEnabled(true);    
imageView.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
imageView.setDrawingCacheEnabled(false);
Community
  • 1
  • 1
Wenger
  • 989
  • 2
  • 12
  • 35
  • 1
    Ok. How can I check quickly if my image still has src="logo.jpg" or a bitmap that I set later. I need to do this really fast. Is there a way to check if the current background image is logo.jpg? – NextDroid Dec 27 '12 at 04:17
  • I am also looking for the answer..The same scenario I have – Anees Deen Oct 28 '14 at 10:29