方向改变时保存对象

Lab*_*lan 36 android android-fragments

如何在方向更改时保存Object,因为不推荐使用onRetainNonConfigurationInstancegetLastNonConfigurationInstance.它不能与我一起使用compatibility package android-support-v4.jar FragmentActivity,它在哪里显示Cannot override the final method from FragmentActivity

开发者网站说

使用新的Fragment API setRetainInstance(boolean)代替;

但我不知道如何使用setRetainInstance保存自定义对象

我的场景:
在我的活动中,我有一个带有进度对话框的AsyncTask.在这里,我需要处理方向变化.
为此,我从Mark Murphy得到了一个非常好的答案,CommonsWare
背景 - 任务 - 进展 - 对话 - 导向 - 改变 - 在那里 - 任何 - 100 - 工作,
示例项目

由于我使用兼容性包android-support-v4.jar FragmentActivity,我无法覆盖onRetainNonConfigurationInstance
无法覆盖FragmentActivity的最终方法

有没有其他方法可以保存我的自定义对象?

编辑: 我不能使我的AsyncTask任务Parcelable(如果我没错),因为它使用接口,上下文等我的AsyncTask

 public class CommonAsyncTask extends AsyncTask<Object, Object, Object>  {
        Context context;
        AsyncTaskServices callerObject;
        ProgressDialog progressDialog;
        String dialogMessag ; 
    ................
Run Code Online (Sandbox Code Playgroud)

我在寻找,是否有onRetainNonConfigurationInstance方法的替代方法,它可以在方向更改时完全保存对象,以后可以使用getLastNonConfigurationInstance

Gio*_*rgi 42

您可以使用onRetainCustomNonConfigurationInstance.

使用它而不是onRetainNonConfigurationInstance().稍后使用getLastCustomNonConfigurationInstance()检索.

  • 有时我觉得这些API比它们应该更加复杂. (15认同)
  • 不,这不一样.见文档:HTTP://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onRetainCustomNonConfigurationInstance \(\)的OP没有说,他试图避免使用onRetain ...() ,他刚才说它没有编译,因为它已经在支持库中被宣布为最终版(这一切都是真的).我认为这种解决方案在迁移到新的工作方式时是有效的保留/解决方法. (5认同)

Nik*_*kov 12

有两种选择:

  1. 用一个Loader.FragmentActivity在重新创建时,它将负责保存/恢复其状态.
  2. 使用没有视图的片段并调用setRetainInstance(true)它.在兼容性库的源代码,FragmentRetainInstanceSupport或其他类似的例子中有一个例子.

  • 还有第三种选择:http://stackoverflow.com/a/11179185/239438 (4认同)

Gra*_*eme 5

当您的片段暂停时,它将调用此方法:

@Override
public void onSaveInstanceState(Bundle outState) {
    // Add variable to outState here
    super.onSaveInstanceState(outState);
}
Run Code Online (Sandbox Code Playgroud)

outState然后,当Fragment重新启动时,该变量将被输入onCreate()方法.

您可以保存任何基本类型的数据或实现Parcelable接口

  • 看我的编辑,我不能让我的AsyncTask任务Parcelable(如果我没错),因为它使用接口,上下文等. (2认同)