how to check if an ImageView is attached with image in android

后端 未结 7 1532
半阙折子戏
半阙折子戏 2020-12-13 05:43

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

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 06:25

    Note that if you set an image via ImageView.setImageBitmap(BITMAP)it internally creates a new BitmapDrawableeven if you pass null. In that case the check imageViewOne.getDrawable() == nullis 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;
    }
    

提交回复
热议问题