旋转时保留 Fragment 对象 [英] Retain the Fragment object while rotating

查看:20
本文介绍了旋转时保留 Fragment 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Honeycomb 中开发了一个应用程序,并且正在使用片段.
这是我的应用

I have developed an app in Honeycomb and I am using fragments.
This is my app

  • 我有一个活动(比如 A1),其中有一个片段
  • 最初这个片段持有对象一个片段对象说(F1)
  • 然后根据用户操作,它可能会更改为其他对象 F2、F3 ....

我的问题是什么

当用户旋转设备时,活动被重新创建,这使得 F1 作为片段对象,即使在旋转之前它不是
旋转时保留fragment对象的方法是什么?
我使用了 setRetainInstance(true); 但它对我不起作用
我在我的 onCreate 函数中按代码添加了这个片段

When The user rotate the device the activity is recreated and which make F1 as the fragment object even though before rotating it wasn't
What is the way to retain the fragment object while rotating?
I used setRetainInstance(true); but it didn't work for me
And I have added the fragment by code in my onCreate function like this

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

   Fragment homeFragment = new Home();
   fragmentTransaction.add(R.id.mainFragement, homeFragment);
   fragmentTransaction.commit();
}

推荐答案

Android 默认会保留片段对象.在您的代码中,您正在 onCreate 函数中设置 homeFragment.这就是为什么它总是一些 homeFragmentfl 您在 onCreate 中设置的内容.

By default Android will retain the fragment objects. In your code you are setting the homeFragment in your onCreate function. That is why it is allways some homeFragment or fl what ever that you set in onCreate.

因为无论何时旋转,onCreate 都会执行并将您的片段对象设置为第一个

所以对您来说最简单的解决方案是检查 savedInstanceState bundle 是否为 null 并设置片段对象

So the easy solution for you is check whether savedInstanceState bundle is null or not and set the fragment object

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

    if(null == savedInstanceState) {
        // set you initial fragment object 
    }
 }

这篇关于旋转时保留 Fragment 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆