1
我有兩個fragment
類和應用程序欄中的兩個按鈕 - 每個按鈕執行下列操作之一:如何在一個活動中切換兩個片段?
- 檢查,如果從其他類別
fragment
存在 - 如果存在,則與新更換容器他
fragment
類的實例 - 如果不存在,創建自己的
fragment
類
這裏的新實例是示例代碼:
private void openReader() {
FragmentManager fragmentManager = getFragmentManager();
ArticleListFragment fragmentList = (ArticleListFragment) fragmentManager.findFragmentById(R.id.action_list);
ArticleReaderFragment fragmentReader = (ArticleReaderFragment) fragmentManager.findFragmentById(R.id.action_reader);
if (fragmentReader==null || ! fragmentReader.isInLayout()) {
if (fragmentList==null || ! fragmentList.isInLayout()) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.container_id, new ArticleReaderFragment());
//ft.addToBackStack(null);
ft.commit();
} else {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container_id, new ArticleReaderFragment());
//ft.addToBackStack(null);
ft.commit();
}
}
else {
// fragment.update(...);
}
}
這裏是activity
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/welcome_page">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container_id">
</FrameLayout>
</LinearLayout>
的問題是,replace
功能不destroying
老fragment
類 - 它被添加在彼此越來越多的片段作爲按鈕被點擊。
任何人都可以告訴我做錯了什麼嗎?