how to check if an ImageView is attached with image in android
Note that if you set an image via ImageView.setImageBitmap(BITMAP)
it internally creates a new BitmapDrawable
even if you pass null
. In that case the check imageViewOne.getDrawable() == null
is false anytime. To get to know if an image is set you can do the following:
private boolean hasImage(@NonNull ImageView view) {
Drawable drawable = view.getDrawable();
boolean hasImage = (drawable != null);
if (hasImage && (drawable instanceof BitmapDrawable)) {
hasImage = ((BitmapDrawable)drawable).getBitmap() != null;
}
return hasImage;
}
imageViewOne.getVisibility() == 0
use this instead:
imageViewOne.getDrawable() == null
From documentation:
/**
* Gets the current Drawable, or null if no Drawable has been
* assigned.
*
* @return the view's drawable, or null if no drawable has been
* assigned.
*
*/
public Drawable getDrawable() {}
The correct way to check if the ImageView is attached with the image is:
if (imageView.getDrawable() == null){
//Image doesn´t exist.
}else{
//Image Exists!.
}
Some methods to load images into the ImageView like using Glide or Picasso have a little delay so we must wait for some milliseconds to check:
//Load Image.
Glide.with(this)
.load(imageURL)
.into(imageView);
//Wait for 500 ms then check!.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (imageView.getDrawable() == null){
//Image doesn´t exist.
}else{
//Image Exists!.
}
}
}, 500