2011-09-25 75 views
1

My FragmentActivity在tabhost中管理4個listfragments(對於每個listfragment,我保留它的backstack的蹤跡)。 ListFragment共享一個FrameLayout,在其中附加他們的內容。當onListItemClick被觸發時,每一個ListFragment讓FragmentActivity開始一個新的Fragment,使得當前片段的內容被新片段替換。 如果您調用A當前顯示(由ListFragment A管理)和B的fragmetn,則會在內容A與B的內容重疊的片段之間切換時發生將替換A(例如由ListFragment B管理)的片段,至少會我清除關閉片段的後臺堆棧(示例中爲A)。在片段之間爲了我做FragmentActivity和Fragments:popBackStack

if (activeTab != tv) { 
     if (activeTab != null) { 
      Log.i(TAG, "tag: " + activeTab.getTag() + " detaching..."); 
      FragmentInfo fragmentInfo = fragments.get(activeTab.getTag()); 
      //detach the current fragment 

      //getSupportFragmentManager().popBackStack((String)activeTab.getTag(), FragmentManager.POP_BACK_STACK_INCLUSIVE); 
      ft.detach(fragmentInfo.fragment); 
     } 

     //get the new 
     FragmentInfo fragmentInfo = fragments.get(tv.getTag()); 
     Log.i(TAG, "tag: " + tv.getTag() + " fragment: " + fragmentInfo.mClass.getName()); 
     if (fragmentInfo != null) { 
      if (fragmentInfo.fragment == null) { 
       fragmentInfo.fragment = Fragment.instantiate(this, fragmentInfo.mClass.getName(), fragmentInfo._args); 
       ft.add(R.id.mytabcontent, fragmentInfo.fragment, fragmentInfo._tag); 
      } else { 
       Log.i(TAG, "attacching fragment: " + fragmentInfo.mClass.getName()); 
       ft.attach(fragmentInfo.fragment); 
      } 
     } 
    } 

而當我需要改變listfragment內容時OnListemItemClick被激發我用

private void replaceFragment(Fragment fragment, String tag, String backstack) { 

    FragmentTransaction ft = manager.beginTransaction(); 
    ft.replace(R.id.mytabcontent, fragment, tag); 
    ft.setTransition(FragmentTransaction.TRANSIT_NONE); 
    ft.addToBackStack(backstack); 
    ft.commit(); 
} 

你能幫我明白爲什麼?在此先感謝和抱歉我的英語不好

編輯:我的問題是爲什麼我需要清理後臺每次我切換ListFragment以避免片段重疊的內容。我做錯了什麼

+0

嘗試重組一點點onTabUnselected ......我不明白有什麼問題。 – Cristian

回答

5

好的,所以這個答案假設你想在每次換標籤時擦掉每個標籤回曆史。我的意思是選項卡1從frag 1開始,然後單擊並將其更改爲frag 2.如果選擇Tab 2,則將撤消Tab 1的歷史記錄,並且下次單擊Tab 1時,您將返回FRAG 1.

隨着這裏說的是解決辦法:更換你用下面

public void onTabUnselected(Tab tab, FragmentTransaction ft) { 
     if (mFragment != null) { 
      //this segment removes the back history of everything in the tab you are leaving so when you click on the tab again you go back to a fresh start 
      FragmentManager man = mActivity.getFragmentManager(); 
      if(man.getBackStackEntryCount()>0) //this check is required to prevent null point exceptions when clicking off of a tab with no history 
       man.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE); //this pops the stack back to index 0 so you can then detach and then later attach your initial fragment 
      //also it should be noted that if you do popbackstackimmediate here instead of just popbackstack you will see a flash as the gui changes back to the first fragment when the code executes 
      //end 
      ft.detach(mFragment); 
     } 
    }