У меня есть два 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
класс - это добавляет все больше и больше фрагментов по сравнению друг с другом, как кнопки щелкают ,
Может ли кто-нибудь сказать, что я делаю неправильно?