How to check if ImageView contains Bitmap or not?
如果
这是代码:_
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | croppedImage = cropImageView.getCroppedImage(); croppedImageView = (ImageView) findViewById(R.id.croppedImageView); croppedImageView.setImageBitmap(croppedImage);@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_save: counter++; if(croppedImageView.getDrawable() != null) { System.out.println("nullllllllllllll"); try { Bitmap photo = ((BitmapDrawable)croppedImageView.getDrawable()).getBitmap(); FileOutputStream mFileOutStream1 = openFileOutput("IMG" + counter +".png", Context.MODE_PRIVATE); photo.compress(CompressFormat.JPEG, 100, mFileOutStream1);} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();} }else{ System.out.println("notttttnullllllllllllll"); try { FileOutputStream mFileOutStream1 = openFileOutput("IMG" + counter +".png", Context.MODE_PRIVATE); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream1); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Editor editor = def.edit(); editor.putInt("value", counter); editor.commit(); break; default: break; } } |
您可以如下检查:
1 2 3 4 5 6 7 | boolean hasDrawable = (croppedImageView.getDrawable() != null); if(hasDrawable) { // imageView has image in it } else { // no image assigned to image view } |
只检查位图值如下:
1 2 3 4 5 | if(bitmap == null) { // set the toast for select image } else { uploadImageToServer(); } |
至少在一种情况下,接受的答案是不正确的:当您之前通过:
将
1 | imageView.setImageBitmap(null); |
实际上它不会将内部
您可以在
1 2 3 4 5 | 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)); } |
意味着不是将其内部
因此,检查
1 2 3 4 5 6 7 | publie static boolean hasNullOrEmptyDrawable(ImageView iv) { Drawable drawable = iv.getDrawable(); BitmapDrawable bitmapDrawable = drawable instanceof BitmapDrawable ? (BitmapDrawable)drawable : null; return bitmapDrawable == null || bitmapDrawable.getBitmap() == null; } |
此外,查看源代码中的这种行为,人们可能会认为