本文介绍了如何确定片段backstack恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直在寻找这个问题的同时,也没有用现在的:

Been searching for this issue for a while to no avail now:

如何确定片段是从backstack恢复?我使用兼容性库和FragmentActivity内ListFragment。当内ListFragment一个项目被选择,一个新的片段开始更换ListFragment

How to determine fragment is being restored from backstack?I'm using the compatibility library and a ListFragment inside a FragmentActivity. When an item inside ListFragment is selected, a new Fragment is started to replace the ListFragment.

我注意到,当FragmentActivity被暂停,该片段的的onSaveInstanceState被调用。但是,当片段放进通过FragmentTransaction后退堆栈,的onSaveInstanceState不会被调用,那么生命周期方法onCreateView和onActivityCreated被调用空savedInstanceState捆绑。

I noticed that when the FragmentActivity gets paused, the Fragment's onSaveInstanceState is called. But when the Fragment is put into the back stack via FragmentTransaction, onSaveInstanceState doesn't get called, then the lifecycle methods onCreateView and onActivityCreated gets called with null savedInstanceState Bundle.

我问,是因为我希望在创建或恢复的片段时加载一些数据,但不能因此当用户通过回来。 backstack。

I'm asking this because I want to load some data when the Fragment is created or restored, but not so when user comes back via. backstack.

我已经看了How检查是否片段从backstack恢复?但要增加更多的细节,希望这会煽动答案。

I've looked at How to check if Fragment was restored from a backstack?but want to add more details in hopes this would incite an answer.

编辑:只注意到http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle)说

just noticed http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle)says

但是请注意:此方法可的onDestroy前随时调用()。有很多情况下,一个片段可能大多是拆掉了,但它的状态不会被保存,直到其所属活动实际上需要保存其状态(当放在后面堆栈没有UI表现,如)。

那么的onSaveInstanceState肯定是出了问题......

So onSaveInstanceState is definitely out of the question...

推荐答案

我认为,最简单的办法就是在onViewCreated做到这一点的例子()方法:

I think that most simple way is do this for example in onViewCreated() method:

if (savedInstanceState == null && !mAlreadyLoaded) {
    mAlreadyLoaded = true;

    // Do this code only first time, not after rotation or reuse fragment from backstack
}

由于Android的时候把片段上backstack,它只会破坏它的观点,但不杀实例本身,就会使mAlreadyLoaded是仍是当片段将从backstack恢复。

Because when android put fragment on backstack, it only destroy its view, but don't kill instance itself, so mAlreadyLoaded will be still true when fragment will be restored from backstack.

这篇关于如何确定片段backstack恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 23:37