ImageView not retaining Image when Screen rotation occurs

后端 未结 5 1274
清酒与你
清酒与你 2021-01-04 18:01
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.ut         


        
5条回答
  •  死守一世寂寞
    2021-01-04 18:45

    The reason why your image disappears when screen rotates is that the activity is destroyed and recreated. During such process, the selected image is not retained as you can read here

    Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

    If you want to retain the selected image you should not use Instance State as you can read here.

    Bundle that the system saves for you with the onSaveInstanceState() callback—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. In such a situation, you can alleviate the burden of reinitializing your activity by retaining a Fragment when your activity is restarted due to a configuration change. This fragment can contain references to stateful objects that you want to retain.

    I implemented this solution and you can find the code in my answer to this other question

提交回复
热议问题