2013-12-08 54 views
1

我發現了一些屬於類似的問題,但我還沒有發現,似乎適合我的具體情況通過片段上返回堆棧遍歷

什麼是通過所有的迭代的正確方法是什麼答案在堆疊上的碎片,爲了對它們進行特定的操作?我需要根據環境的變化更新一些片段並刪除一些片段(理論上,我可以在片段再次獲得焦點並採取適當的動作時捕獲一個事件,但這會使事情變得複雜一些, M還處理事情越來越重命名)

鑑於該片段的容器如下:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/fragment_container" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" /> 

並添加片段如下:

FragmentTransaction transaction = context.getSupportFragmentManager().beginTransaction(); 
Fragment fragment = new CustomFragment(); 

transaction.add(R.id.fragment_container, fragmentBase); 
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
transaction.addToBackStack(nameOfFragment); 

transaction.commit(); 

context.getSupportFragmentManager().executePendingTransactions(); 

我第一次迭代的嘗試是:

getSupportFragmentManager().executePendingTransactions(); 
for (int indexFragment = 0; indexFragment < getSupportFragmentManager().getBackStackEntryCount(); indexFragment++) 
{ 
    FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager().getBackStackEntryAt(indexFragment);      

    // If Android keeps the ID, surely there should be a way of getting to the actual fragment itself, from that ID? 
    Fragment fragment = getSupportFragmentManager().findFragmentById(backStackEntry.getId());     

    if (fragment != null) 
    {    
     //TODO: Cast the fragment and perform some transactions against it 

     // We never get here; as fragment is always null 
    } 
} 

從不同的角度:

FrameLayout frameLayout = (FrameLayout)findViewById(R.id.fragment_container); 

for (int indexFrameLayout = 0; indexFrameLayout < frameLayout.getChildCount(); indexFrameLayout++) 
{ 
    View view = (View)frameLayout.getChildAt(indexFrameLayout); 

    // I get the right number of views; but I can't interact with them as fragments 
} 

我可以,假設,砍我的方式過去的這個問題,通過保持對片段的引用,但也有這種做法的問題。

  • 有沒有一種方法可以得到當前在背後的碎片?

  • 假設我可以得到一個片段,是否有一種方法可以從後臺堆棧中的某個地方移除它(單獨它)? (還有就是transaction.remove方法,但是是爲了對坐在後面堆中間片段工作?)

感謝

+0

另一個問題回答了這個好: http://stackoverflow.com/questions/9772790/get-all-fragments-from-backstack-in-order – afollestad

回答

0

BackStackEntry不是單Fragment相關的必要,它表示一個FragmentManager狀態,你可能在事務中有一堆碎片,因此在一個狀態中有一堆碎片。使用add()方法的this flavor方法,並通過標籤爲您的片段分配唯一的ID。然後,你就可以通過getSupportFragmentManager().findFragmentById(fragment_tag);

至於你的任務是找到他們,AFAIK有沒有辦法從BackStack刪除任意狀態,你唯一的選擇是彈出堆棧中的其他從頂部之後,除去一個狀態。因此,您可以覆蓋您的onBackPressed()並致電fragmentManager.popBackStack()以簡單地轉到以前的狀態或fragmentManager.popBackStack(backstack_tag)以跳過某些狀態並轉到需要的地方。