我有兩個片段的活動。一個片段以縱向顯示,另一個以橫向模式顯示。片段用java添加。Android碎片分離
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();
}
}
我的問題是,如果我開始了我在縱向模式下的活動,當我旋轉如預期,但在肖像片段onActivityCreated被稱爲太顯示景觀片段的畫面。這意味着肖像片段仍然存在。你能告訴我我的錯誤在哪裏嗎?
您不需要手動分離片段。試着替換它們。 – eleven 2014-10-06 12:44:01