java Android:remove()Fragment>add()再次添加同一类的新片段>onCreateView和onActivityCreated未调用?
我正在用以下方法销毁一个通过编程创建的片段:
getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.test)).commit();
这在xml文件中确定,如下所示:
<LinearLayout
安卓:id="@+id/test"
安卓:orientation="horizontal"
安卓:layout_width="fill_parent"
安卓:layout_height="fill_parent">
</LinearLayout>
如果我在mainactivity中再次从同一个类创建一个片段:
getSupportFragmentManager().beginTransaction()
.add(R.id.result_bar, testinstance)
.commit();
然后onCreate似乎不再被调用(片段只是空的)。我做错了什么?谢谢
# 1 楼答案
说明:为什么要使用FrameLayout for Fragment
什么是
FrameLayout
根据Google Documentation on Commons Layouts和What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?的这个答案,
ViewGroup
作为LinearLayout
、RelativeLayout
、AbsoluteLayout
(decrepated)、TableLayout
等允许显示视图:等等
FrameLayout
按重叠显示视图。它通常用于包含布局:来源:FrameLayout MobilTuts
来源:Android Frame Layout For Absolute Beginner
好的,但是,为什么我需要这个呢?(vs线性布局或<;片段>;)
报告说:
FrameLayout
将主持一个布局,并且它愿意这样做。而其余的ViewGroup
只显示视图。你可以在所有的ViewGroup
s中制作一个Fragment
(我测试过,这对我来说是一个惊喜),但这不是一个正确的方法。这些FrameLayout
是:如果你用
<fragment .../>
创建一个布局,你的片段将不会被另一个替换,因为它被显示,它在视图上用它的id“附着”。要替换片段,您需要将其托管:“通过将片段封装在FrameLayout中,您可以只替换细节”(请参见this answer)然后,请记住
FrameLayout
是空的,可以承载布局Fragment
s(Fragment Documentation from Google,它非常简单地解释了如何使用片段的事实),当它们用xml声明时,它们必须附加一个类(一个id),这个id不能被替换这就是为什么我们需要一个容器来承载这个片段,并重叠该活动的视图
希望这会有帮助
注意:如果有人想编辑这个答案,因为它没有解释或解释得不好,她/他可以发自肺腑