有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    说明:为什么要使用FrameLayout for Fragment

    什么是FrameLayout

    根据Google Documentation on Commons LayoutsWhat are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?的这个答案,ViewGroup作为LinearLayoutRelativeLayoutAbsoluteLayout(decrepated)TableLayout等允许显示视图:

    1. LinearLayout:“逐个显示视图”
    2. RelativeLayout:“显示与其他视图相关的视图”
    3. TableLayout:“在表格中显示视图”
      等等

    FrameLayout重叠显示视图。它通常用于包含布局:

    "Frame layouts are one of the simplest and most efficient types of layouts used by Android developers to organize view controls. They are used less often than some other layouts, simply because they are generally used to display only one view, or views which overlap. The frame layout is often used as a container layout, as it generally only has a single child view (often another layout, used to organize more than one view)."

    来源:FrameLayout MobilTuts

    "The Frame layout allows developers to display only a single or multiple UI elements within Frame Layout but each element will be positioned based on the top left of the screen, and elements that overlap will be displayed overlapping."

    来源:Android Frame Layout For Absolute Beginner

    好的,但是,为什么我需要这个呢?(vs线性布局或<;片段>;)

    报告说:

    "FrameLayout is designed to block out an area on the screen to display a single item."

    FrameLayout将主持一个布局,并且它愿意这样做。而其余的ViewGroup只显示视图。你可以在所有的ViewGroups中制作一个Fragment(我测试过,这对我来说是一个惊喜),但这不是一个正确的方法。这些FrameLayout是:

    "...the normal layout of choice when you want to overlap views."

    如果你用<fragment .../>创建一个布局,你的片段将不会被另一个替换,因为它被显示,它在视图上用它的id“附着”。要替换片段,您需要将其托管:“通过将片段封装在FrameLayout中,您可以只替换细节”(请参见this answer

    然后,请记住FrameLayout是空的,可以承载布局Fragments(Fragment Documentation from Google,它非常简单地解释了如何使用片段的事实),当它们用xml声明时,它们必须附加一个类(一个id),这个id不能被替换
    这就是为什么我们需要一个容器来承载这个片段,并重叠该活动的视图

    希望这会有帮助

    注意:如果有人想编辑这个答案,因为它没有解释或解释得不好,她/他可以发自肺腑