How to keep an image in an Android activity during an orientation change?
Bitmap image;
public void onCreat(..){
if (savedInstanceState != null) {
image = (Bitmap) savedInstanceState.getParcelableExtra("BitmapImage");;
} else {
image = yourBitmapImage;
}
}
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putExtra("BitmapImage", bitmap);
}
I think it costs too much if you save a Bitmap
in onSaveInstanceState
,as onSaveInstanceState
will be called before onStop
every time,and Bitmap
is a big thing.
I think is better to save a URI
in onSaveInstanceState
。
Uri mUri;
ImageView mImageView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (savedInstanceState != null){
mUri = savedInstanceState.getParcelable("uri");
mImageView.setImageURI(mUri);
}
}
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
...
mUri = targetUri;
}
}
public void onSaveInstanceState(Bundle outState) {
if (mURI !=null) {
outState.putParcelable("uri", mUri);
}
}
We should never use the above way to save our heavy objects such as image or bitmap it is always advisable to use the fragments. Have a look at this an easy implementation of how to retain the fragment https://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject