第二次方向改变后的图像显示

时间:2014-05-03 16:39:41

标签: android screen-orientation

我使用以下代码保存和恢复图像,它在第一个方向更改后工作(纵向到横向)。然而,在我将其旋转回肖像模式(第二个方向更改)后,图像消失了,我不想发生这种情况。

请帮忙

保存图片代码

 @Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putParcelable("selectedImage", yourSelectedImage);


}

恢复代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
if(savedInstanceState !=null){
        Bitmap yourSavedBitmap = savedInstanceState.getParcelable("selectedImage");
        image.setImageBitmap(yourSavedBitmap);

    }



}

3 个答案:

答案 0 :(得分:0)

您正在使用两个不同的变量来保存实例并恢复实例:

yourSelectedImage

yourSavedBitmap

所以我假设您正在从代码中的其他位置设置var yourSelectedImage,将其序列化为已保存的实例,但在恢复后该变量为空。如果可能的话,可以使用:

yourSelectedImage = yourSavedBitmap

在还原实例代码中。

答案 1 :(得分:0)

public class MainActivity extends Activity {

private Bitmap bmp;
private ImageView image;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    image = (ImageView)findViewById(R.id.image);

    // first time the app is started get the bitmap from unknown source.
    if(savedInstanceState == null) { 
        bmp = BitmapFactory.decodeFile("file location string");
    // after orientation change get your saved bitmap
    } else { 
        bmp = savedInstanceState.getParcelable("selectedImage");
    }
    image.setImageBitmap(bmp);
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putParcelable("selectedImage", bmp );
}
}

答案 2 :(得分:0)

好吧,我现在可以自己回答。 我把一个preferenceManger存储为一个字符串:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString(selectImage,"selected").commit();

并在每次创建应用时调用它:

savedImage = PreferenceManager.getDefaultSharedPreferences(this).getString("selectImage", "-1");
    try {
       if (savedImage != null) {
           InputStream imageStream = null;
           try {
               imageStream = getContentResolver().openInputStream((Uri.parse(savedImage)));
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           }
           Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
           image.setImageBitmap(yourSelectedImage);

       }
    } catch (Throwable e){
       e.printStackTrace();

    }