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?
Keep it simple
:: Replacing Fragment
= Removing Current Fragment
+ Adding New Fragment
Sample
:: Modify to your needs with saveInstance
and other things
Boolean mFlag=false;
{
Fragment fragment = null;
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
if(mFlag==false)
FragmentPortrait();
mFlag=true;
} else {
if(mFlag==true)
FragmentLandscape();
mFlag=false;
}
FragmentPortrait(){
// Perform Action:: Replacing a fragment with the fragment you want to add in Portrait
}
FragmentLandscape(){
// Perform Action:: Replacing a fragment with the fragment you want to add in Landscape
}
}