Android 如何在从另一个活动返回后恢复活动中最后打开的片段

Android 如何在从另一个活动返回后恢复活动中最后打开的片段,android,android-fragments,fragment,android-listfragment,Android,Android Fragments,Fragment,Android Listfragment,我在这样一个活动中使用了多个片段:片段A在它的项目上有一个列表单击片段B打开,它也有一个列表打开片段C有一个列表打开另一个活动,问题是当我从另一个活动返回时,我发现片段A打开了,从其他活动返回时,如何恢复最后一个片段C 下面是在我的活动中替换片段的代码 protected void showFragment(Fragment fragment) { String TAG = fragment.getClass().getSimpleName(); FragmentTransa

我在这样一个活动中使用了多个片段:片段A在它的项目上有一个列表单击片段B打开,它也有一个列表打开片段C有一个列表打开另一个活动,问题是当我从另一个活动返回时,我发现片段A打开了,从其他活动返回时,如何恢复最后一个片段C

下面是在我的活动中替换片段的代码

 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();
}
你可以用

 fragmentTransaction.addToBackStack(null);
而不是

 fragmentTransaction.addToBackStack(TAG);

希望您的问题能够解决。

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

使用“添加”而不是“替换”

fragmentTransaction.add(R.id.container_home, fragment, TAG);
我使用上述代码解决了相同的问题。

查看答案