【问题标题】:how to restore last opened fragment inside an activity after getting back from another actvivty从另一个活动返回后如何恢复活动中最后打开的片段
【发布时间】:2020-03-20 06:20:37
【问题描述】:

我在这样的流程中使用多个片段:片段 A 在其项目上有一个列表单击片段 B 打开,它还有一个列表打开片段 C 有一个列表打开另一个活动,问题是当我从另一个Activity返回我发现Fragment A已打开,从另一个Activity返回时如何恢复上一个Fragment C?

这是在我的活动中替换 Fragment 的代码

 protected void showFragment(Fragment fragment) {

    String TAG = fragment.getClass().getSimpleName();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.container_home, fragment, TAG);
    fragmentTransaction.addToBackStack(TAG);
    fragmentTransaction.commit();
}

【问题讨论】:

标签: android android-fragments fragment android-listfragment


【解决方案1】:

replace 删除现有片段并添加新片段。这意味着当您按下返回按钮时,将创建被替换的片段并调用其 onCreateView。而 add 保留现有的 Fragment 并添加一个新的 Fragment,这意味着现有的 Fragment 将处于活动状态。

使用添加而不是替换

fragmentTransaction.add(R.id.container_home, fragment, TAG);

我用上面的代码解决了同样的问题。

【讨论】:

    【解决方案2】:

    你可以使用

     fragmentTransaction.addToBackStack(null);
    

    而不是,

     fragmentTransaction.addToBackStack(TAG);
    

    希望你的问题能解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多