ImageView - 图像在方向变化时丢失

时间:2015-03-22 04:59:49

标签: android

我有一个应用程序,我拍照并将其设置为图像按钮上的图像。在方向改变时,图像消失。请帮忙。

我单击图片并将其设置为ImageItem上的图像

public void onImageButtonClicked(View view)
{
    Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(camIntent, TAKE_PHOTO);
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == TAKE_PHOTO && resultCode == Activity.RESULT_OK)
        try {
            InputStream stream = getContentResolver().openInputStream(data.getData());
            Bitmap bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            ImageButton imageButton = (ImageButton) findViewById(R.id.itemImage);

            int mDstWidth = getResources().getDimensionPixelSize(R.dimen.destination_width);
            int mDstHeight = getResources().getDimensionPixelSize(R.dimen.destination_height);

            scaledBmp = Bitmap.createScaledBitmap(bitmap, mDstWidth, mDstHeight, true);
            imageButton.setImageBitmap(scaledBmp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    super.onActivityResult(requestCode, resultCode, data);
}

当方向改变时,图像消失。

I saved the image in 

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
    super.onSaveInstanceState(savedInstanceState);
    if (scaledBmp != null) {
        savedInstanceState.putByteArray("image", getBitmapAsByteArray(scaledBmp));
    }
}


and retrieved in 

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    byte[] savedImage;
    savedImage = savedInstanceState.getByteArray("image");
    if (savedImage != null) {
        scaledBmp = BitmapFactory.decodeByteArray(savedImage, 0, savedImage.length -1);
    }
}

我现在应该手动设置按钮上的图像吗?有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

我错过了onResume()

protected void onResume()
{
    super.onResume();
    if (scaledBmp != null)
    {
        ImageButton ib = (ImageButton) findViewById(R.id.itemImage);
        if (ib != null)
            ib.setImageBitmap(scaledBmp);
    }
}

随着这一变化,事情开始奏效。我正在以横向和纵向模式获取图像。

Asthme的评论帮助了我,谢谢。