[英]How to check if ImageView contains Bitmap or not?
我正在實現如果ImageView
有位圖,那么它應該將圖像從imageview保存到內部存儲器,否則在應用程序的內部存儲器中設置另一個位圖。 這是代碼:_
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;
}
}
您可以按如下方式檢查:
boolean hasDrawable = (croppedImageView.getDrawable() != null);
if(hasDrawable) {
// imageView has image in it
}
else {
// no image assigned to image view
}
只需檢查Bitmap值,如下所示:
if(bitmap == null) {
// set the toast for select image
} else {
uploadImageToServer();
}
對於至少一種情況, 接受的答案 是不正確的:當您之前通過以下方式將ImageView
的Bitmap
設置為null
:
imageView.setImageBitmap(null);
實際上它不會將內部Drawable
設置為null
。 因此,在接受的答案檢查中提出的建議會給你不正確的結果。
您可以輕松找到ImageView
源代碼中發生的事情:
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));
}
這意味着它不是將其內部Drawable
設置為null
,而是將其設置為具有null
Bitmap
的新創建的BitmapDrawable
。
因此, 檢查ImageView
是否有一些有意義的Drawable
的正確方法是這樣的:
publie static boolean hasNullOrEmptyDrawable(ImageView iv)
{
Drawable drawable = iv.getDrawable();
BitmapDrawable bitmapDrawable = drawable instanceof BitmapDrawable ? (BitmapDrawable)drawable : null;
return bitmapDrawable == null || bitmapDrawable.getBitmap() == null;
}
此外,在源代碼中查看此行為,可能會認為null
Drawble
是Android SDK開發人員試圖避免的。 這就是為什么你應該避免依賴於getDrawable() == null
檢查你的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.