我正在尝试用我根据通过网络连接返回的一些信息生成的 fragment 完全替换 fragment 返回堆栈。我首先将返回堆栈弹出到我想要的位置(工作正常......但为了简单起见,我假设我弹出到根),然后我尝试构建并应用这样的 fragment 堆栈:
ArrayList<JSONObject> crumbsOut = new ArrayList<JSONObject>(count);
//.... pop the back stack to a certain point
//replace entire nav. backstack
final FragmentTransaction transaction = this.getActivity().getSupportFragmentManager().beginTransaction();
for(int i = 0; i<count; i++)
{
final JSONObject item = crumbsOut.get(i);
final String id = item.getString("id");
FolderFragment currentFolder = new FolderFragment();//fragment displays folder contents
Bundle args = new Bundle();
args.putString(DATA_ITEM_ID_KEY, id);
args.putString(DATA_ITEM_NAME_KEY, item.getString("displayname"));
currentFolder.setArguments(args);
transaction.replace(R.id.MasterContainer, currentFolder);
transaction.addToBackStack(id);
}
// Commit the transaction
transaction.commit();
当我运行它时,最顶层的 FolderFragment 会正确显示,但是当我点击后退按钮(或弹出堆栈)时, View 会立即恢复到运行上述代码之前的点(即,而不是返回在我用循环创建的新 fragment 堆栈中,我返回到尝试添加/创建此堆栈之前的状态)。
如果有帮助,我正在我的项目中使用 Android 兼容包。
请帮忙。谢谢
最佳答案
我找到了答案。您必须为要添加到堆栈中的每个新 fragment 创建唯一的事务。我原本认为这不是必需的,但我想事实并非如此。所以,这里是答案:
ArrayList<JSONObject> crumbsOut = new ArrayList<JSONObject>(count);
//.... pop the back stack to a certain point
//replace entire nav. backstack
for(int i = 0; i<count; i++)
{
//move the transaction into the loop
final FragmentTransaction transaction = this.getActivity().getSupportFragmentManager().beginTransaction();
final JSONObject item = crumbsOut.get(i);
final String id = item.getString("id");
FolderFragment currentFolder = new FolderFragment();//fragment displays folder contents
Bundle args = new Bundle();
args.putString(DATA_ITEM_ID_KEY, id);
args.putString(DATA_ITEM_NAME_KEY, item.getString("displayname"));
currentFolder.setArguments(args);
transaction.replace(R.id.MasterContainer, currentFolder);
transaction.addToBackStack(id);
// Commit the transaction
//move the commit into the loop
transaction.commit();
}
关于java - 用新堆栈替换 fragment 返回堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6259501/