我在应用程序栏中有两个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
类 - 它会在点击按钮时相互添加越来越多的碎片。
有谁能说出我做错了什么?
答案 0 :(得分:0)
我犯了很多错误:
由于我无法动态设置片段ID,我需要使用标签
ft.replace(R.id.container_id, new ArticleListFragment(), "Action_list");
或
ft.add(R.id.container_id, new ArticleListFragment(), "Action_list");
我只需要使用findFragmentByTag()
因为isInLayout()
总是给我错误。
以下是该功能的工作版本:
private void openList() {
FragmentManager fragmentManager = getFragmentManager();
ArticleListFragment fragmentList = (ArticleListFragment) fragmentManager.findFragmentByTag("Action_list");
ArticleReaderFragment fragmentReader = (ArticleReaderFragment) fragmentManager.findFragmentByTag("Action_reader");
if (fragmentList==null) {
if (fragmentReader==null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.container_id, new ArticleListFragment(), "Action_list");
//ft.addToBackStack(null);
ft.commit();
} else {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container_id, new ArticleListFragment(), "Action_list");
//ft.addToBackStack(null);
ft.commit();
}
}
else {
// fragment.update(...);
}
}