gpt4 book ai didi

android - 应用程序恢复时在列表数据上保存状态

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:15 24 4
gpt4 key购买 nike

这是我的设置。

我有一个 Main SherlockFragmentActivity。它用 FragmentTransaction 来回交换许多 ListFragments。为了指示加载,任何时候 ListFragment 都会加载我调用的数据:

setSupportProgressBarIndeterminateVisibility(true);

问题:

当上面提到的主要 Activity 第一次 启动时,或者用户离开并转到其他应用程序,然后在一段较长的时间后重新启动这个应用程序SherlockFragmentActivity貌似重新加载,ActionBar没有进度对话框,白屏几秒,然后列表数据修复(长度取决于数据连接)。

这是一些补充代码:当主/基础 Activity 首次加载时,这是我在 onCreate() 中做的第一件事:

// Set up Main Screen
FragmentTransaction t2 = this.getSupportFragmentManager().beginTransaction();
SherlockListFragment mainFrag = new FollowingFragment();
t2.replace(R.id.main_frag, mainFrag);
t2.commit();

FollowingFragment 将始终在此实例中加载。它包含一个 ListView 和一个 AsyncTaskMySQL 数据库中提取数据。

我的问题:如何防止这种延迟?当用户长时间离开时,我如何处理维护数据?

最佳答案

这是正常行为,发生这种情况是因为当您的应用程序处于后台时,您的 Activity 已被终止以节省其他应用程序的内存。当它回到前台时,系统会重新创建您的 Activity ,这将重新创建您的 fragment 。

但是如果您真的想避免重新创建您的 fragment ,您可以在 fragment 的 onCreate 方法中使用 setRetainInstance:

public void setRetainInstance (boolean retain)

Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:

onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity). onCreate(Bundle) will not be called since the fragment is not being re-created. onAttach(Activity) and onActivityCreated(Bundle) will still be called.

然后在 FragmentActivity 的 onActivityCreated 方法中使用类似这样的方法:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

FragmentManager fm = getFragmentManager();

// Check to see if we have retained the worker fragment.
mRetainableFragment = (RetainedFragment)fm.findFragmentByTag("fragmentTag");

// If not retained (or first time running), we need to create it.
if (mRetainableFragment == null) {
mRetainableFragment = new RetainedFragment();
// Tell it who it is working with.
mRetainableFragment.setTargetFragment(this, 0);
fm.beginTransaction().add(mRetainableFragment, "fragmentTag").commit();
}
}

但请注意,这应该只用于 headless fragment (没有 UI 的 fragment ,即在 onCreateView 中返回 null,又名工作 fragment )。您仍然可以将此方法用于 UI fragment ,但谷歌不推荐使用此方法,在这种情况下,数据必须作为成员(字段)存储在您的 Activity 中。如果 Bundle 类支持应存储的数据,则可以使用 onSaveInstanceState() 方法将数据放入 Bundle 中,并在 onActivityCreated() 方法中检索该数据。

此外,这仅在 fragment 未添加到后台堆栈时才有效。

关于android - 应用程序恢复时在列表数据上保存状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17792956/

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