保留片段对象,同时旋转片段、对象

2023-09-12 11:01:11 作者:鹤归孤山

我已经开发了蜂窝的应用程序,我使用的片段。 这是我的应用程序

在我有一个活动(说A1)和有一个片段 在开始时,该片段保存对象一个片段对象说(F1) 然后根据用户的动作可能会改成其他对象F2,F3 ......

我的问题是

当用户旋转设备的活动,并重新创建这使得F1的片段对象,即使之前转动它不是 什么是保留片段对象,同时旋转的方式? 的 我用 setRetainInstance(真); ,但它并没有为我工作 而且我已经加入该片段由code在我的的onCreate 这样的功能

  @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        //端添加
        的setContentView(R.layout.main);
            FragmentTransaction fragmentTransaction = getFragmentManager()的BeginTransaction()。
            片段homeFragment =新的主页();
            fragmentTransaction.add(R.id.mainFragement,homeFragment);
            fragmentTransaction.commit();
        }
 

解决方案

在默认情况下Android将保留片段对象 在您的code您正在设置 homeFragment 的onCreate 功能。这就是为什么它是永诺某些 homeFragment FL 您在设置什么都的onCreate 因为每当你转动,的onCreate将执行和设置您的片段对象第一个 所以,你最简单的办法是检查是否 savedInstanceState 捆绑为空或不并设置片段对象

  @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        如果(空== savedInstanceState){
             //设置你的初始片段对象
        }
  }
 
分享几个超级适合女生的副业,努力一点绝对是有收益的 视频

希望它帮助你。

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

I have an Activity (Say A1) and in that there is a fragment Initially this fragment hold the object one fragment object say (F1) Then depending on the user actions it may change to other objects F2,F3 ....

What my problem is

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);
        // End Addition
        setContentView(R.layout.main);
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            Fragment homeFragment = new Home();
            fragmentTransaction.add(R.id.mainFragement, homeFragment);
            fragmentTransaction.commit();
        }

解决方案

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 Because whenever you rotate, the onCreate will execute and set your fragment object to the first one 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 
        }
  }

Hope it helped you