我正在使用Android Studio,我按下了一个按钮打开我的三星星系相机并拍了一张照片。然后我可以保存图片并将其显示在应用程序内的imageview中。但是,从今天起,图片不会显示在imageview中。它仍然可以保存,但在我拍照后会消失。如果我侧身拿着手机,图像会首先显示,但是一旦我将设备拉直,图像就会消失。我不明白这是什么,我是Android工作室的新手和一般的编码。如果有人可以帮助,将不胜感激:)?此外,当图像消失时,日志中会出现此错误:32351-32351 / com.andyexample.myapplication E / ViewRootImpl:sendUserActionEvent()mView == null。
主要活动代码:
公共类MainMenu扩展了ActionBarActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
//Drawable dirty;
//Bitmap bitmapImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
imageView = (ImageView) findViewById(R.id.imageView);
Button openCamera = (Button) findViewById(R.id.openCamera);
Button buttonFilter = (Button) findViewById(R.id.buttonFilter);
}
//launching the camera
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take the picture taken along to a result activity
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
//if you want to save image
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get Photo
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
imageView.setImageBitmap(photo);
}
}
答案 0 :(得分:0)
正如@Squonk所描述的那样,旋转设备时位图会丢失,因为活动被销毁并重新创建(以便它可以在新方向上创建它的布局)。
因此,您需要在活动被销毁时保存位图,并在重新创建活动时将其读回。
您可以按照以下方式执行此操作:
// save the Activity's instance state as it gets destroyed
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("bitmap", bitmap);
}
// restore any saved instance state
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
imageView = (ImageView) findViewById(R.id.imageView);
if (savedInstanceState != null) {
bitmap = savedInstanceState.getParcelable("bitmap");
}
if(bitmap != null) {
imageView.setImageBitmap(photo);
}
}
请注意,您必须制作'位图' Activity的实例成员,而不是局部变量。
答案 1 :(得分:0)
我找到了你的问题。我也遇到了这个问题。但是这可以通过保存uri和saveInstance并恢复savedInstance来解决。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get Photo
Uri mImageCaptureUri = data.getData();
imageView.setImageUri(mImageCaptureUri);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mImageCaptureUri != null) {
outState.putString("cameraImageUri", mImageCaptureUri.toString());
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
mImageCaptureUri = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}