FindFragementByTag后片段没有活动错误

时间:2015-08-25 21:09:30

标签: android android-fragments

我有一个包含多个片段的主要活动。这就是我如何切换片段

  public void openFragment(final Fragment fragment, String title, String tag){
        getSupportFragmentManager().popBackStack();
        getSupportFragmentManager()
                .beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .add(R.id.container, fragment, tag)
                .addToBackStack(null)
                .commit();
        getSupportActionBar().setTitle(title);
    }

我在主活动中有一个INT变量,我从每个片段更新以确定在方向更改之前哪个片段处于活动状态

private int ACTIVE_FRAGMENT = 0;

在Activity上保存的实例中,我像这样保存INT

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(Constants.ACTIVE_EVENT_ID, ACTIVE_FRAGMENT);
    super.onSaveInstanceState(outState);
}

onRestoreInstanceState我会像这样回到Active Fragment

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    if (savedInstanceState != null){
        ACTIVE_FRAGMENT = savedInstanceState.getInt(Constants.ACTIVE_EVENT_ID);
        if (ACTIVE_FRAGMENT > 0){
            FragmentManager fm = getSupportFragmentManager();
            switch (ACTIVE_FRAGMENT) {
                case 1:
                    EventSetupFragmentOne fragmentOne = (EventSetupFragmentOne) fm.findFragmentByTag(Constants.SETUP_FRAGMENT_ONE_TAG);
                    if (fragmentOne != null) {
                        openFragment(fragmentOne, getString(R.string.event_setup_title_1), Constants.SETUP_FRAGMENT_ONE_TAG);
                    }
                    break;
            }
        }
    }
}

这可以追溯到Active Fragment但是然后抛出No Actitiy found异常

 Caused by: java.lang.IllegalStateException: No activity
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1125)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1120)
            at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1929)

在配置更改后,如何以不同的方式返回Active Fragment?

1 个答案:

答案 0 :(得分:1)

您无需在配置更改时调用openFragment。 片段将由框架重新创建。

这就是为什么在onCreate方法中,如果savedInstanceState == null你没有(重新)初始化你的碎片。