如何保存片段?当我旋转屏幕

问题描述:

可能重复:
ViewPager and fragments — what's the right way to store fragment's state?如何保存片段?当我旋转屏幕

我怎么可以保存片段? (它位于活动)当我旋转屏幕,正在重新启动活动,片段是重新创建enter image description here

+0

保护无效的onCreate(捆绑savedInstanceState){ super.onCreate(savedInstanceState)使用setRetainInstance(true);; ... CustomFragment fragment;如果(savedInstanceState!= null){ fragment =(CustomFragment)getSupportFragmentManager()。findFragmentByTag(“customtag”); } else { fragment = new CustomFragment(); ();。add().id(container,fragment,“customtag”)。commit(); } ... } – Viral

+0

通过以下代码我发布了您可以保存片段状态。 – Viral

您需要添加方向安卓configChanges在AndroidManifest.xml中。每例如:

android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" 
+0

向我解释这是什么意思? –

+0

从http://developer.android.com/guide/topics/manifest/activity-element.html陈述: _列出活动将自行处理的配置更改。当运行时发生配置更改时,该活动默认关闭并重新启动,但使用此属性声明配置将会阻止活动重新启动。相反,活动仍然在运行,并调用其onConfigurationChanged()方法._ –

+0

是的,但它为什么会使用onSaveInstanceState和onRestoreInstanceState?也许这个http://stackoverflow.com/a/12214737/1568164 –

尝试在你的片段的onCreate

+1

我认为这会给我以下 - 我会保留所有的片段,但我需要保存片段 –

+0

搜索我开始明白,这是一些东西你可以添加一些例子 –