【问题标题】:Iterating through fragments on the backstack遍历 backstack 上的片段
【发布时间】:2013-12-08 21:07:14
【问题描述】:

我发现了许多类似的问题,但我没有找到任何似乎适合我的具体情况的答案

为了对每个片段执行特定的操作,迭代 backstack 上的所有片段的正确方法是什么?我需要根据环境的变化更新一些片段并删除一些片段(理论上,我可以在片段再次获得焦点时捕获一个事件,然后采取适当的行动,但这会使事情变得有点复杂,因为我' 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 方法,但它是用来处理位于后堆栈中间的片段吗?)

谢谢

【问题讨论】:

标签: android android-fragments back-stack


【解决方案1】:

BackStackEntry 不必与单个Fragment 关联,它代表FragmentManager 状态,您可能在事务中有一堆碎片,因此在一个状态中有一堆碎片。使用this flavoradd() 方法并通过标签为您的片段分配一个唯一的ID。然后你就可以通过getSupportFragmentManager().findFragmentById(fragment_tag);找到他们

至于您的任务,afaik 无法从BackStack 中删除任意状态,您唯一的选择是弹出堆栈,从顶部依次删除一个状态。例如,您可以覆盖您的onBackPressed() 并调用fragmentManager.popBackStack() 以简单地转到上一个状态或fragmentManager.popBackStack(backstack_tag) 跳过某些状态并转到您需要的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-30
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2017-04-08
    • 1970-01-01
    • 2012-03-24
    相关资源
    最近更新 更多