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

你说的曾经没有我的故事 提交于 2019-11-27 03:18:57

问题


Is is possible to use FragmentTransaction and the remove() method to get rid of fragments that are defined in the layout.xml (using the fragment tag) ?

I did not get 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?

It is possible to replace a fragment that is defined in the lyaout.xml, so I find it a bit strange that it should not be possible to remove it?


回答1:


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




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/8903874/can-i-remove-a-fragment-defined-in-a-layout-xml-file

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