堆栈中碎片的Android恢复顺序



我有2个活动,A和B。每个活动都是碎片的容器,碎片被FragmentTransaction代替。

我在某些设备上遇到了一个问题,即用户在活动A中打开活动B时,第一个活动可能会破坏,这意味着当用户单击后面按钮时,它会使第一个活动在IN中重新创建一种普通的设备,它只会恢复。

我的主要问题是,用户失去了他在第一个活动中拥有的片段堆栈。当用户打开第二个活动时,他已经是3个片段"深"的第一个活动。我如何恢复堆栈并将用户返回到第一次活动被摧毁之前的观点?

这应该由Android OS自动处理。您可以将开发人员选项"不要保留活动"始终模仿这种行为(破坏您的活动),当您的活动进入后台时。之后,您可以开始调试。有些需要检查的事情:

  • 在活动中,您是在调用超级on CreateSavedinstancestate?

  • 如果您在ongreate的开始时放了一个断点,那么回到活动,是否有保存的实例状态?

  • 您在哪里创建片段?你是在重新创建他们吗手动(您不应该)?

  • 是您的片段在布局中进行了硬编码或在布局中替换(更换容器视图)?

*编辑 *

从您的答复中,我得出的是问题,您说:"在造成的末尾,我正在用片段交易代替片段,从而加载了应用程序的第一个片段" =>您不应该这样做当SavedinStancestate不是零时。否则,您将销毁从保存状态中已经存在的东西。

在这里检查:https://developer.android.com/training/basics/fragments/fragment-ui.html

请注意,当SavedinStancestate不为null时,返回。

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);
        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {
            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            // Create a new Fragment to be placed in the activity layout
            HeadlinesFragment firstFragment = new HeadlinesFragment();
            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}

最新更新