I am setting an image to ImageView in android code not in xml, but could not make out how to check whether that image has been set in or not in java.
Tried with
ImageView myImage = (ImageView) findViewById(R.id.imageView);
if (myImage.getDrawable() == null){
//The imageView is empty
} else{
// The imageView is occupied.
}
or
ImageView myImage = (ImageView) findViewById(R.id.imageView);
if ( null == myImage.getDrawable()){
//The imageView is empty
} else{
// The imageView is occupied.
}
imageViewOne.getVisibility() == 0
use this instead:
imageViewOne.getDrawable() == null
if (img_like.getTag() != null && img_like.getTag().toString().equals("red")) {
img_like.setImageResource(R.drawable.heart);
img_like.setTag("heart");
} else {
img_like.setImageResource(R.drawable.red);
img_like.setTag("red");
}
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;
}
You can do imageViewOne.getDrawable() for the image you set on the src attribute - meaning setImageResource/Bitmap. Or imageViewOne.getBackground() for the background attribute - meaning setBackground.
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