FragmentManager 不删除动态添加的片段
FragmentManager Not Removing Dynamically added Fragments
我正在尝试 add/remove DialogFragments
to/from 我的 FragmentManager
动态地作为用户执行不同的操作。问题是 FragmentManager
没有正确删除所有这些。我正在调用 remove()
函数,所以我很好奇为什么这些 Fragments
没有被删除。我在网上搜索过,remove 方法是人们所说的从 FragmentManager
.
中删除 Fragments
应该使用的方法
下面的示例代码显示了我在做什么:
// originally added `LoginRestFragment` with TAG_LOGIN_REST_FRAGMENT tag to Fragment Manager
rest = new SettingsDialogFragment();
FragmentManager fm = getFragmentManager();
rest.setArguments(bundle);
Fragment fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("frag_type", fragment.toString());
fm.beginTransaction().remove(fragment).commit();
fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("is_frag_removed", fragment.toString());
// why does this return a Fragment type ^^ shouldn't it throw null errror?
Log.d("rest", rest.toString());
// ^ this shows rest has been updated from LoginRestFrament to SettingsDialogFragment
fm.beginTransaction().add(rest, TAG_LOGIN_REST_FRAGMENT).commit();
fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("frag_type", fragment.toString());
// why is this not SettingsDialogFragment??
显示所代表内容的日志语句。我应该注意到屏幕上显示的不再是 LoginRestFragment,而是 SettingsDialogFragment
(正如预期的那样),rest 是一个 class 变量。
D/frag_type: LoginRestFragment
D/is_frag_removed: LoginRestFragment
D/rest: SettingsDialogFragment
D/frag_type: LoginRestFragment
谢谢DeeV!你说的是真的,这就是我找到解决方法的方法,在 this Whosebug 条目中得到了回答。您基本上可以在 FragmentManager
上使用 executePendingTransactions()
来动态提交。
我正在尝试 add/remove DialogFragments
to/from 我的 FragmentManager
动态地作为用户执行不同的操作。问题是 FragmentManager
没有正确删除所有这些。我正在调用 remove()
函数,所以我很好奇为什么这些 Fragments
没有被删除。我在网上搜索过,remove 方法是人们所说的从 FragmentManager
.
Fragments
应该使用的方法
下面的示例代码显示了我在做什么:
// originally added `LoginRestFragment` with TAG_LOGIN_REST_FRAGMENT tag to Fragment Manager
rest = new SettingsDialogFragment();
FragmentManager fm = getFragmentManager();
rest.setArguments(bundle);
Fragment fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("frag_type", fragment.toString());
fm.beginTransaction().remove(fragment).commit();
fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("is_frag_removed", fragment.toString());
// why does this return a Fragment type ^^ shouldn't it throw null errror?
Log.d("rest", rest.toString());
// ^ this shows rest has been updated from LoginRestFrament to SettingsDialogFragment
fm.beginTransaction().add(rest, TAG_LOGIN_REST_FRAGMENT).commit();
fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
Log.d("frag_type", fragment.toString());
// why is this not SettingsDialogFragment??
显示所代表内容的日志语句。我应该注意到屏幕上显示的不再是 LoginRestFragment,而是 SettingsDialogFragment
(正如预期的那样),rest 是一个 class 变量。
D/frag_type: LoginRestFragment
D/is_frag_removed: LoginRestFragment
D/rest: SettingsDialogFragment
D/frag_type: LoginRestFragment
谢谢DeeV!你说的是真的,这就是我找到解决方法的方法,在 this Whosebug 条目中得到了回答。您基本上可以在 FragmentManager
上使用 executePendingTransactions()
来动态提交。