I have an app which uses the NavigationDrawer.
I switch fragments like this:
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
public void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
String fragmentTag = String.valueOf(position);
FragmentBase fragment = (FragmentBase) fragmentManager
.findFragmentByTag(fragmentTag);
if (null == fragment) {
fragment = createFragmentByPosition(position);
}
if (null == fragment)
return;
if (fragment.isAdded()) {
fragmentTransaction.show(fragment);
} else {
fragmentTransaction.add(R.id.content_frame, fragment, fragmentTag);
}
if (mCurrentFragment != null) {
fragmentTransaction.hide(mCurrentFragment);
}
mCurrentFragment = fragment;
fragmentTransaction.commitAllowingStateLoss();
mDrawerList.setItemChecked(position, true);
setTitle(mNoterActivities[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
private FragmentBase createFragmentByPosition(int position) { // FragmentBase just extends Fragment
FragmentBase fragment = null;
if (position == 0) {
fragment = new Fragment1();
Bundle args = new Bundle();
fragment.setArguments(args);
} else if (position == 1) { // Reminder
fragment = new Fragment2();
Bundle args = new Bundle();
fragment.setArguments(args);
}
return fragment;
}
In the onCreate() method, I do selectItem(0).
I was previously using android:configChanges="keyboardHidden|orientation|screenSize"
for the Activity
, but I would now like to start creating different layouts for different screen sizes and orientations. I cannot do this using appropiately named folders if this code is in the manifest.
So, I decided to remove it (I couldn't remember why I had it anyway!). However, by doing this, whenever the orientation changes, the fragment that is shown is still the same but the action bar changes to another fragments configuration (I think the previously shown fragment), and if I then try to switch fragments, the action bar changes (also to the previously shown fragment, I think), but the shown fragment does not change.
What does not work:
Changing the .add
to .replace
When some configurations changed, such as orientation, the app will be restarted, the the view will be recreated,
onCreate
will be called.When the view is re-created, the ActionBar will turn to the origin state.
But if you add
android:configChanges="keyboardHidden|orientation|screenSize"
to theManifest.xml
, theonConfigurationChanged
will be called instead ofonCreate
, the view will not be re-created.update1
You should keep android:configChanges="keyboardHidden|orientation|screenSize", then change the layouts after the change of screen sizes and orientation occurs, in the method:
onConfigurationChanged
.Here are some examples: Handling Runtime Changes