NavigationDrawer を使用するアプリがあります。
次のようにフラグメントを切り替えます。
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;
}
onCreate() メソッドでは、selectItem(0) を実行します。
以前は を使用 android:configChanges="keyboardHidden|orientation|screenSize"
していましたActivity
が、さまざまな画面サイズと向きに合わせてさまざまなレイアウトの作成を開始したいと考えています。このコードがマニフェストにある場合、適切な名前のフォルダーを使用してこれを行うことはできません。
それで、私はそれを削除することにしました(とにかく、なぜ持っていたのか思い出せませんでした!)。ただし、これを行うと、向きが変わるたびに、表示されるフラグメントは同じままですが、アクションバーは別のフラグメント構成に変わります (以前に表示されたフラグメントだと思います)。その後、フラグメントを切り替えようとすると、アクションバー(以前に表示されたフラグメントにも変更されると思います)が、表示されているフラグメントは変更されません。
機能しないもの:
を変更.add
する.replace