【问题标题】:Replace fragment back stack with new stack用新堆栈替换片段返回堆栈
【发布时间】:2011-06-07 00:23:19
【问题描述】:

我正在尝试用我根据通过网络连接返回的一些信息生成的片段完全替换片段回栈。我首先将返回堆栈弹出到我想要的位置(效果很好......但为了简单起见,我可以说我弹出到根),然后我尝试构建并应用这样的片段堆栈:

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 正确显示,但是当我点击后退按钮(或弹出堆栈)时,视图恢复到运行上述代码之前的点(即,而不是返回在我使用循环创建的新片段堆栈中,我回到尝试添加/创建此堆栈之前的状态)。

如果有帮助,我将在我的项目中使用 Android 兼容包。

请帮忙。谢谢

【问题讨论】:

    标签: java android-fragments android


    【解决方案1】:

    我找到了答案。您必须为要添加到堆栈中的每个新片段创建唯一的事务。我原本以为这没有必要,但我想不是这样。所以,这里是答案:

    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();
    }
    

    【讨论】:

      【解决方案2】:

      可能是您在同一个方法中执行所有操作,而您的 beginTransaction() 调用正在取消弹出(FragmentManager 无疑会开始执行弹出的事务)。-

      我建议自己使用相同的 FragmentTransaction 进行清理,并且只执行一次提交。或者,您可以将替换调用发布到主线程消息队列中,以便稍后执行。

      当您使用 compat 库时,您可以随时调试源代码以查看发生了什么。

      【讨论】:

      • 嗯……即使我注释掉出栈的代码,结果也是一样的;只有循环中的最后一个片段被添加到堆栈中,然后返回将我返回到上述代码提交之前的状态。另外,“我建议使用相同的 FragmentTransaction 自己进行清理......”是什么意思?谢谢。
      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 2011-04-29
      • 2019-07-11
      相关资源
      最近更新 更多