【问题标题】:how can I save the fragment? when I rotate the screen [duplicate]如何保存片段?当我旋转屏幕时[重复]
【发布时间】:2012-09-04 20:32:45
【问题描述】:

可能重复:
ViewPager and fragments — what's the right way to store fragment's state?

如何保存片段? (位于activity处)当我旋转屏幕时,activity被重启,fragment被重新创建

【问题讨论】:

  • 受保护的 void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... CustomFragment 片段; if (savedInstanceState != null) { fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag"); } else { 片段 = 新的 CustomFragment(); getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit(); } ... }
  • 按照上面我发布的代码,你可以保存片段状态。

标签: android android-fragments


【解决方案1】:

尝试在片段的 onCreate 中使用 setRetainInstance(true);

【讨论】:

  • 我认为这会给我以下信息 - 我将保留片段中的所有内容,但我需要保存片段
  • 搜索我开始明白这是一个东西你可以添加一些例子
【解决方案2】:

您需要在 AndroidManifest.xml 中将 orientation 添加到 android:configChanges。举例:

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

【讨论】:

  • 向我解释这是什么意思?
  • 来自developer.android.com/guide/topics/manifest/… 声明:列出活动将自行处理的配置更改。当运行时发生配置更改时,默认情况下会关闭并重新启动 Activity,但使用该属性声明配置会阻止 Activity 重新启动。相反,Activity 保持运行并调用其 onConfigurationChanged() 方法。
  • 是的,它有效,但为什么人们使用 onSaveInstanceState 和 onRestoreInstanceState ?也许这个stackoverflow.com/a/12214737/1568164
  • 这看起来很难看,但效果很好!!!!谢谢。
  • 作品,但我根本不推荐它。只是期望您的活动将被重新创建。因此,您的 onPause() 需要将您需要长时间生存的任何内容存储到永久存储中,但轮换只需要您覆盖 onSaveInstanceState 并填写捆绑包。对于专门用于旋转的片段,setRetainInstance(true) 实际上将处理人们在旋转时想要的大部分行为。
猜你喜欢
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多