public class MyOnCheckedChangeListener implements OnCheckedChangeListener {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (mAppsFragment != null) {
ft.hide(mAppsFragment);
}
if (mPhoneFragment != null) {
ft.hide(mPhoneFragment);
}
if (mEmailFragment != null) {
ft.hide(mEmailFragment);
}
if (mSettingsFragment != null) {
ft.hide(mSettingsFragment);
}
switch (checkedId) {
case R.id.main_tab_apps:
if (mAppsFragment == null || mAppsFragment.getActivity() == null) {
mAppsFragment = new AppsFragment();
ft.add(R.id.realtabcontent, mAppsFragment);
} else {
ft.show(mAppsFragment);
}
ft.commit();
break;
case R.id.main_tab_phone:
if (mPhoneFragment == null || mPhoneFragment.getActivity() == null) {
mPhoneFragment = new PhoneFragment();
ft.add(R.id.realtabcontent, mPhoneFragment);
} else {
ft.show(mPhoneFragment);
}
ft.commit();
break;
case R.id.main_tab_email:
if (mEmailFragment == null || mEmailFragment.getActivity() == null) {
mEmailFragment = new EmailFragment();
ft.add(R.id.realtabcontent, mEmailFragment);
} else {
ft.show(mEmailFragment);
}
ft.commit();
break;
case R.id.main_tab_setting:
if (mSettingsFragment == null || mSettingsFragment.getActivity() == null) {
mSettingsFragment = new SettingsFragment();
ft.add(R.id.realtabcontent, mSettingsFragment);
} else {
ft.show(mSettingsFragment);
}
ft.commit();
break;
}
}
}
private void detachFragments() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (mAppsFragment != null) {
ft.remove(mAppsFragment);
mAppsFragment = null;
}
if (mPhoneFragment != null) {
ft.remove(mPhoneFragment);
mPhoneFragment = null;
}
if (mEmailFragment != null) {
ft.remove(mEmailFragment);
mEmailFragment = null;
}
if (mSettingsFragment != null) {
ft.remove(mSettingsFragment);
mSettingsFragment = null;
}
}
ft.detach(fragment):
onPause, onStop, onDestroyView
ft.remove(fragment):
onPause, onStop, onDestroyView, onDestroy and onDetach
ft.attach(fragment):
onCreateView, onStart and onResume
ft.add(fragment):
onAttach, onCreate, onCreateView, onStart and onResume
描述:
You'll notice that when a Fragment is detached, its onPause, onStop and onDestroyView methods are called only (in that order). On the other hand, when a Fragment is removed, its onPause, onStop, onDestroyView, onDestroy and onDetach methods are called (in that order). Similarly, when attaching, the Fragment's onCreateView, onStart and onResume methods are called only; and when adding, the Fragment's onAttach, onCreate, onCreateView, onStart and onResume methods are called (in that order).