gpt4 book ai didi

Android - 为什么使用 onSaveInsanceState() 来保存未调用的位图对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:45:21 25 4
gpt4 key购买 nike

我正在制作一个简单的绘图应用程序。

我希望能够在设备方向改变时保存用户在屏幕上的绘图。这只发生在主要 Activity 中。

我读到,如果方向发生变化,那么 Activity 将被销毁并再次重新创建(onCreate(Bundle created) 被调用)。我不确定这是否意味着它也应该调用 onSavedInstanceState(Bundle bundle),因为在我的应用程序中,只有当另一个 Activity 将焦点放在我的主要 Activity 之上时才会调用它,而不是当旋转到横向/纵向。

我只是在寻找一种方法来保存现有位图,并在方向发生变化时将其传递给主要 Activity 。如果我的 onSaveInstanceState 从未被调用,我该怎么办?

此外,由于 Bitmap 实现了 parceable,我已经使用了它。

这是主要 Activity 的代码:

 public void onCreate(Bundle savedInstanceState) {      
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// some more activity code...

if (savedInstanceState != null) {
bitmap = savedInstanceState.getParcelable("bitmap");
Log.d("STATE-RESTORE", "bitmap created");
paintBoard.setBitmapBackground(bitmap, false);
Log.d("RESTORING...", "onRestoreInstanceState()");
} else {
Log.d("SavedInstanceState", "null");
}
}


// Never called when I change orientation on my device
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
bitmap = Bitmap.createBitmap(paintBoard.getBitmap());
outState.putParcelable("bitmap", bitmap);
Log.d("STATE-SAVE", "onSaveInstanceState()");
}

我们将不胜感激。

编辑:

我从 AndroidManifest.xml 文件中删除了这一行:

android:configChanges="orientation"

现在 onSaveInstanceState() 在我改变设备方向时会被调用。

最佳答案

你应该阅读 this article完全。

...it might not be possible for you to completely restore your activity state with the 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 stateful Object when your activity is restarted due to a configuration change.

To retain an object during a runtime configuration change:

  1. Override the onRetainNonConfigurationInstance() method to return the object you would like to retain.
  2. When your activity is created again, call getLastNonConfigurationInstance() to recover your object.

关于Android - 为什么使用 onSaveInsanceState() 来保存未调用的位图对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com