2014-10-06 142 views
0

我有兩個片段的活動。一個片段以縱向顯示,另一個以橫向模式顯示。片段用java添加。Android碎片分離

Fragment fragment = null; 
     if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { 
      fragment = new FragmentPortrait(); 
     } else { 
      fragment = new FragmentLandscape(); 
     } 

     if (fragment != null) { 
      addFragment(fragment, savedInstanceState == null); 
     } 

private void addFragment(Fragment fragment, boolean add) { 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager 
       .beginTransaction(); 

     detachFragment("fragment"); 

     if (add) { 
      fragmentTransaction.add(R.id.layoutForFragment, fragment, 
        "fragment"); 
     } else { 
      fragmentTransaction.replace(R.id.layoutForFragment, 
        fragment, "fragment"); 
     } 

     fragmentTransaction.commit(); 
    } 

private void detachFragment(String fragmentTag) { 
     Fragment fragment = getSupportFragmentManager().findFragmentByTag(
       fragmentTag); 

     if (fragment != null) { 
      Log.i(TAG, "detaching"); 
      getSupportFragmentManager().beginTransaction().remove(fragment) 
        .commit(); 
     } 
    } 

我的問題是,如果我開始了我在縱向模式下的活動,當我旋轉如預期,但在肖像片段onActivityCreated被稱爲太顯示景觀片段的畫面。這意味着肖像片段仍然存在。你能告訴我我的錯誤在哪裏嗎?

+1

您不需要手動分離片段。試着替換它們。 – eleven 2014-10-06 12:44:01

回答

0

Keep it simple :: Replacing Fragment = Removing Current Fragment + Adding New Fragment


Sample :: 修改與saveInstance您的需求和其他的東西


Boolean mFlag=false; 
{ 
     Fragment fragment = null; 

     if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { 
     if(mFlag==false) 
      FragmentPortrait(); 
      mFlag=true; 
     } else { 
     if(mFlag==true) 
      FragmentLandscape(); 
      mFlag=false; 
     } 

     FragmentPortrait(){ 
     // Perform Action:: Replacing a fragment with the fragment you want to add in Portrait 
     } 

     FragmentLandscape(){ 
     // Perform Action:: Replacing a fragment with the fragment you want to add in Landscape 
     } 

} 
+0

我沒有之前的分離方法,但注意到這個問題,並嘗試使用它,但它仍然無法正常工作..我會修復我的代碼,但是當我改變(例如)從縱向到橫向時,你能告訴我爲什麼該肖像的onActivityCreated也被稱爲? – definera 2014-10-06 13:23:28

+0

@ Crash-ID ....'onActivityCreated'將被調用,因爲片段被破壞並創建! .......但我不知道爲什麼'OnOrientation'從肖像變爲風景,爲什麼人物的onActivityCreated也被稱爲........如果你想通過限制使用'flags' ...因爲全局變量不會在'OnOrientation'類中被破壞! ......檢查編輯! ....希望它可以幫助...'注意''修改標誌設置以滿足您的需求! – Devrath 2014-10-06 13:47:47