片段onCreate在重新加载片段时多次调用

时间:2014-01-29 06:51:04

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

以下是我的代码:

public class MyListFragmentActivity extends FragmentActivity{

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.out.println("DEBUG : MLFA onCreate");
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(fragmentID, new MyListFragment())
            .replace(detailFragmentID, new MyDetailFragment()).commit();
        }
    }



     @Override
    protected void onRestart() {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            Fragment prevFrag = getSupportFragmentManager().findFragmentById(detailFragmentID);
    if (prevFrag != null) {
        fragmentTransaction.remove(prevFrag);
        getSupportFragmentManager().beginTransaction().replace(detailFragmentID, new MyDetailFragment()).commitAllowingStateLoss();
    } else {
        getSupportFragmentManager().beginTransaction().replace(detailFragmentID, new MyDetailFragment()).commitAllowingStateLoss();
    }
}

MyListFragment

public class MyListFragment extends Fragment{

//When we click on each item in list view call detail fragment to relad its layout
OnItemClickListener onItemClickListener = new OnItemClickListener() {

/** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        /** Getting the existing detailed fragment object, if it already exists.
        *  The fragment object is retrieved by its tag name
        * */
        Fragment prevFrag = getFragmentManager().findFragmentById(detailFragmentID);

        /** Remove the existing detailed fragment object if it exists */
        if (prevFrag != null) {
            fragmentTransaction.remove(prevFrag);
           MyDetailFragment mydetailFragment = new MyDetailFragment();
            fragmentTransaction.replace(detailFragmentID, mydetailFragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.show(getFragmentManager().findFragmentById(detailFragmentID));
            fragmentTransaction.commit();
        }
}

MyDetailFragment

public class MyDetailFragment extends Fragment{

onCreate() // on create being called multiple times ? why ?????????????

onCreateView()

}

当我点击我的列表项时,MyDetailFragment onCreate()只被调用一次,但当我将设备倾斜为纵向或横向时,MyDetailFragment onCreate()被多次调用?

为什么这样?我在这里做错了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

每次更改方向时,都会重新启动应用程序。您需要适当地处理更改,例如释放资源,再次获取资源,停止正在进行的任何工作以及恢复它们等等。

你没有做错任何事。