【发布时间】: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 方法,但它是用来处理位于后堆栈中间的片段吗?)
谢谢
【问题讨论】:
-
另一个问题更好地回答了这个问题:stackoverflow.com/questions/9772790/…
标签: android android-fragments back-stack