FragmentManager不删除动态添加的片段

时间:2016-08-26 17:19:14

标签: android android-fragments fragmentmanager

我正在尝试向用户DialogFragments添加/删除FragmentManager,因为用户执行不同的操作。问题是FragmentManager未正确删除所有这些内容。我正在调用remove()函数,所以我很好奇为什么这些Fragments没有被删除。我在线搜索过,删除方法就是人们说你应该使用的方法,以便从Fragments删除FragmentManager

下面的示例代码显示了我在做什么:

            // 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是一个类变量。

D/frag_type: LoginRestFragment
D/is_frag_removed: LoginRestFragment
D/rest: SettingsDialogFragment
D/frag_type: LoginRestFragment

1 个答案:

答案 0 :(得分:1)

谢谢DeeV!你说的是真的,这就是我在this StackOverflow条目中找到解决方法的方法。您基本上只需在executePendingTransactions()上使用FragmentManager即可动态提交。