Android: Orientation changes erase modifications made to my ImageView

大城市里の小女人 提交于 2019-12-06 11:18:35

When a configuration change such as a screen rotation occurs by default your Activity is destroyed and then recreated (onDestroy of the current activity is called, and then the onCreate of a new version of your activity is called).

You can either:

  • Stop Android recreating your activity when a configuration change occurs. To do this add android:configChanges="keyboardHidden|orientation" to the activity tag in your manifest. This is not recommend since if you want a different layout etc for different configurations you will have to handle changing the layout yourself.
  • Override onRetainNonConfigurationInstance and return your bitmap from that. In onCreate check if the last non-configuration instance is not null, in which case cast it to a bitmap and then set the image.

For the latter case, use something like the following:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    // Check if our activity was just destroyed and re-created
    final Object retainedFromConfigChange = getLastNonConfigurationInstance();
    if (retainedFromConfigChange != null) {
        // Activity has just been recreated, get the image we were working on
        // before the configuration change
        ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
        iv.setImageBitmap((Bitmap) retainedFromConfigChange);
    }

    ...
}

@Override
public Object getLastNonConfigurationInstance() {
    ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
    // We have to return a plain old Bitmap and not a drawable of any sorts
    // or we will get memory leaks so we need to extract the bitmap from the drawable
    return ((BitmapDrawable) iv.getDrawable()).getBitmap();
}
Jana

i think you have a solution in this link.

https://stackoverflow.com/questions/456211/activity-restart-on-rotation-android

I think you forgot to override the onRetainNonConfigurationInstance() method where you return your bitmap so it will be passed to the new activity. In the new activity you can retrieve the bitmap as you already do by calling getLastNonConfigurationInstance().

When the configuration is changed, the whole view is re-created. So, we need to retain the imageView resource. The best way to do this is to handle the orientation change by creating a Retained fragment.

You can find the perfect documentation on Android developer's page.

P.S.: Adding android:configChanges="keyboardHidden|orientation" to the manifest is highly not recommended.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!