我有两个片段(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()
然后被删除.为什么会这样?
在Fragment生命周期方法中,使用此方法打开调用 onPause() - > onStop() - > onDestroyView() - > onDestroy() - > onDetach().
addToBackStack(null)
方法将片段添加到backStack,即保存片段实例,当片段变为不可见时,系统调用片段onDestroyView()
方法因为视图被破坏,但系统调用方法之后onDestroy()
因为片段实例保存在backStack中并且片段实例上有引用而且它没有不要毁灭.如果实例未被破坏,系统会将该实例附加到活动而不会调用onDetach()
它.