片段:onCreate被调用4次

时间:2014-01-28 05:48:51

标签: android android-fragments fragment android-fragmentactivity android-listfragment

我有一个片段的工作模型,当我调试代码时,我看到片段onCreate被调用了4次。

以下是我的代码: 的 MyFragmentActivity

class MyFragmentActivity extends FragmentActivity{

@Override
    public void onCreate(Bundle savedInstanceState) {
      if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(fragmentID, new MyListFragmentt())
            .replace(detailFragmentID, new MyDetailFragment()).commit();
        }
}

@Override
    protected void onRestart() {
        getSupportFragmentManager().beginTransaction().replace(detailFragmentID, new MyDetailFragment()).commitAllowingStateLoss();
}

}

MyDetailFragment.class

class MyDetailFragment extends Fragment{

// has method like oncreate(),onCreateView(),onSaveInstanceState()
}

如何调用MyDetailFragment的oncreate?当我去其他一些活动然后回来然后只倾斜设备然后多次调用oncreate和MyDetailFragment的onSaveInstance状态。

我如何解决这个问题,我已经在SO上查了几篇文章,但它说我们需要使用HIDE,Show方法和其他东西?但对此有什么适当的灵魂?

修改

当我从之前的活动回来时,MyDetailFragment中的数据需要刷新。

2 个答案:

答案 0 :(得分:0)

    i think ur recreating fragments multiple times, u do new MyListFragment everytime on onCreate function, call findFragmentByTag to get the existing fragment and set that, if null (first time) then create one

/ 这里有一些代码配合,如果这不起作用,你的应用程序有单个片段更好地只创建xml并且只有一个片段标记,并在setContentView函数中设置xml * /

    // declare following member variable
    MyFragment _fragment;

    // in onCreate function, call this method

    private void setupFragment()
    {
         _fragment = (MyFragment)getFragmentManager().findFragmentByTag("MyFragment");
         if(null == _fragment)
         {
    _fragment = new MyFragment();
    }
    // now do the fragment transaction
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.add(containerId, _fragment, "MyFragment"); // here tag is important
trans.commit();
    }

答案 1 :(得分:0)

试试这个

MyDetailFragment fragment = new MyDetailFragment();
@Override
    public void onCreate(Bundle savedInstanceState) {
      if (savedInstanceState == null) {

        getSupportFragmentManager().beginTransaction().replace(fragmentID, new MyListFragmentt())
            .replace(detailFragmentID, fragment).commit();
        }
}

@Override
    protected void onRestart() {
        if(fragment != null) {
        getSupportFragmentManager().beginTransaction().replace(detailFragmentID, fragment).commitAllowingStateLoss();
        }
}