How to check if ImageView contains Bitmap or not?

倖福魔咒の 提交于 2019-11-29 08:00:00
Amulya Khare

You can check it as follows:

boolean hasDrawable = (croppedImageView.getDrawable() != null);
if(hasDrawable) {
    // imageView has image in it
}
else {
    // no image assigned to image view
}

Just check only Bitmap value as below :

if(bitmap == null) {
    // set the toast for select image
} else {
    uploadImageToServer();
}

The accepted answer is not correct for at least one case: when you previously set ImageViews Bitmap to null via:

imageView.setImageBitmap(null);

actually it would NOT set the internal Drawable to null. So, the proposed in the accepted answer check will give you incorrect result.

You can easily find out what's going on in the ImageView source code:

 public void setImageBitmap(Bitmap bm) {
     // if this is used frequently, may handle bitmaps explicitly
     // to reduce the intermediate drawable object
     setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
 }

Meaning that instead of setting its internal Drawable to null, it sets it to a newly created BitmapDrawable with null Bitmap.

Therefore, the correct method of checking whether an ImageView has somewhat meaningful Drawable is something like:

publie static boolean hasNullOrEmptyDrawable(ImageView iv)
{
    Drawable drawable = iv.getDrawable();
    BitmapDrawable bitmapDrawable = drawable instanceof BitmapDrawable ? (BitmapDrawable)drawable : null;

    return bitmapDrawable == null || bitmapDrawable.getBitmap() == null;
}

Moreover, looking at this behavior in the source code, one might suppose that null Drawble is something Android SDK developers try to avoid. That's why you should avoid relying on getDrawable() == null check in your code at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!