5

時多次調用下面是我的代碼:片段的onCreate重裝片段

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() 

} 

當我點擊我的名單上item MyDetai lFragment onCreate()僅被調用一次,但是當我將設備傾斜到縱向或橫向時,MyDetailFragment onCreate()會被多次調用?

爲什麼這麼說?我在這裏做錯了什麼,以及如何解決這個問題?

回答

0

每次更改方向時,它都與重新啓動應用程序一樣好。您需要適當地處理更改,例如釋放資源,再次獲取資源,停止正在進行的任何工作並恢復它們等等。

你沒有做錯什麼。

+0

如何解決我的情況?它只需調用MyDetailFragment的onCreate方法 – Goofy

+0

查看生命週期並根據需要進行更改:http://developer.android.com/reference/android/app/Fragment.html#Lifecycle =) –

+0

我在做完全如他們在生命週期中所展示的那樣?但仍然爲什麼這個傳道者一次又一次地被調用? – Goofy