我替换片段时没有调用Android onDetach()

时间:2017-01-26 10:37:16

标签: android fragment

我有两个片段(FRAGMENT_1,FRAGMENT_2)。 FRAGMENT_1正在运行计时器,当我打开FRAGMENT_2时,我希望FRAGMENT_1继续运行它。

onCreate()中的FRAGMENT_1:

if (savedInstanceState == null) {
    FRAGMENT_1 fragment1= new FRAGMENT_1();
    fragment1.setRetainInstance(true);
    getSupportFragmentManager()
        .beginTransaction()
        .add(R.id.main_fragment_container, fragment1, FRAGMENT_1_TAG)
        .addToBackStack(null)
        .commit();
}

这是我在片段之间的导航:

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    String fragTag = "";
    switch (id) {
        case R.id.nav_frag_1:
            //this method returns
            //getSupportFragmentManager().getFragments()
            //.contains(getSupportFragmentManager().findFragmentByTag(tag))
            if (isFragmentCreated(FRAGMENT_1_TAG)) {
                fragment = getSupportFragmentManager()
                        .findFragmentByTag(FRAGMENT_1_TAG);
            } else {
                fragment = new FRAGMENT_1();
            }
            fragTag = FRAGMENT_1_TAG;
            break;

        case R.id.nav_frag_2:
            fragment = new FRAGMENT_2();
            fragTag = FRAGMENT_2_TAG;
            break;

        case R.id.nav_settings:
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            break;

    }
    if (fragment != null && !fragment.isVisible()) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_fragment_container, fragment, fragTag);
        if (fragment.getTag().equals(FRAGMENT_1_TAG)){
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

当我在这些片段之间导航时,FRAGMENT_2不会调用onDetach()因此不会删除它,但如果我删除了以下代码:

if (fragment.getTag().equals(TIMER_FRAGMENT_TAG)){
    fragmentTransaction.addToBackStack(null);
}

然后FRAGMENT_2调用onDetach()然后删除。为什么会这样?

1 个答案:

答案 0 :(得分:8)

在Fragment生命周期方法中,用于在此回合中销毁调用 onPause() - > onStop() - > onDestroyView() - > onDestroy() - > onDetach()

addToBackStack(null)方法将片段添加到backStack,即它保存片段实例,当片段变得不可见时,系统调用片段onDestroyView()方法,因为视图被破坏,但是在系统调用方法之后{ {1}}因为片段实例保存在backStack中,并且片段实例上有引用,并且它不会被破坏。如果实例未被破坏,系统会将该实例附加到活动中,并且不会调用onDestroy()