0

我有一個問題:我想用另一個替換一個片段。所以我寫了這個代碼:Android碎片:多個變化 - 應用程序崩潰

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction(); 
    Fragment statistics = new Statistics(); 
    Fragment home = new Home(); 
    mTransaction.add(R.id.container, home); 
    mTransaction.commitAllowingStateLoss(); 
    mTransaction.replace(R.id.container, statistics); 
    mTransaction.commitAllowingStateLoss(); 

的XML:

 <LinearLayout 
     android:id="@+id/container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 
     </LinearLayout> 

的問題是,只有一個.commitAllowingStateLoss()調用是好的,如果我做兩次(如上)的應用程序崩潰。不幸的是我需要多次調用它。這同樣適用於.commit()。我究竟做錯了什麼?

謝謝!

+0

你爲什麼要添加一個片段,然後立即用另一個替換它?只是一個實驗? –

+0

發佈你的logcat – Rami

回答

0

因爲在致電.commit ..後,交易視爲關閉。 所以我覺得你只需要刪除你的第一個叫.commit 因此,代碼將

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction(); 
Fragment statistics = new Statistics(); 
Fragment home = new Home(); 
mTransaction.add(R.id.container, home); 
mTransaction.replace(R.id.container, statistics); 
mTransaction.commitAllowingStateLoss(); 

如果你仍然想調用.commit 2倍,只是另一個開始交易後第一次提交:

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction(); 
Fragment statistics = new Statistics(); 
Fragment home = new Home(); 
mTransaction.add(R.id.container, home); 
mTransaction.commitAllowingStateLoss(); 
mTransaction = getSupportFragmentManager().beginTransaction(); 
mTransaction.replace(R.id.container, statistics); 
mTransaction.commitAllowingStateLoss();