Android : Android Fragment detach

on Monday, October 6, 2014


I have an activity with two fragments. One fragment is shown in portrait, the other in landscape mode. The fragments are added with java.



Fragment fragment = null;
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
fragment = new FragmentPortrait();
} else {
fragment = new FragmentLandscape();
}

if (fragment != null) {
addFragment(fragment, savedInstanceState == null);
}

private void addFragment(Fragment fragment, boolean add) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();

detachFragment("fragment");

if (add) {
fragmentTransaction.add(R.id.layoutForFragment, fragment,
"fragment");
} else {
fragmentTransaction.replace(R.id.layoutForFragment,
fragment, "fragment");
}

fragmentTransaction.commit();
}

private void detachFragment(String fragmentTag) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag(
fragmentTag);

if (fragment != null) {
Log.i(TAG, "detaching");
getSupportFragmentManager().beginTransaction().remove(fragment)
.commit();
}
}


My problem is that if I started my activity in Portrait mode and when I rotate the screen the landscape fragment is shown as expected but onActivityCreated in the portrait fragment is called too. This means that the portrait fragment still exists. Can you tell me where is my mistake?


0 comments:

Post a Comment