Can I remove a fragment defined in a layout.xml file?

本小妞迷上赌 提交于 2019-11-28 09:58:43
David C. Sainte-Claire

The native APIs available starting in Honeycomb work the same as those in the support libarary, so you cannot remove an instance of a Fragment which has been declared in your layout XML file.

With FragmentTransactions you manipulate ViewGroups such as LinearLayouts that act as containers to hold the layout of other Fragments. However, when you declare a Fragment in your layout, it doesn't have a container in the same sense because it is permanently part of the View hierarchy, so you can't remove it. That is by design, to support things like navigation Fragments that you'd never remove anyways. :)

One thing that's interesting, and I found it out totally by accident, is that you can add new Fragments into a Fragment that was declared with the tag in your layout; and it acts as a container for other Fragments

I did not this to work using the support libraries v4. The fragment stays in place after you commit the FragmentTransaction, after calling remove(). Can anyone tell me if this is by design, a bug or a feature?

This is by design (or a lack of a feature, not definitely a feature if you ask me :P). So as long as you are using the support libraries, you can't achieve this.

Like @david-c-sainte-claire and @martín-marconcini said, you can't use remove() method and FragmentTransaction to remove the fragment that was defined in the XML. That doesn't mean you are out of luck. You can always use setVisibility() method.

findViewById(R.id.fragment_main).setVisibility(View.GONE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!