gpt4 book ai didi

java - Android: remove() Fragment--> add() new Fragment of same class again ->onCreateView and onActivityCreated 没有被调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:54:43 24 4
gpt4 key购买 nike

我正在销毁一个以编程方式创建的 fragment :

getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.test)).commit();

在xml文件中是这样决定的:

<LinearLayout
android:id="@+id/test"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

</LinearLayout>

如果我在主 Activity 中再次从同一个类创建一个 fragment :

getSupportFragmentManager().beginTransaction()
.add(R.id.result_bar, testinstance)
.commit();

然后 onCreate 似乎不再被调用( fragment 只是空的)。我在这里做错了什么?谢谢。

最佳答案

说明:Fragment为什么要用FrameLayout

什么是FrameLayout :

根据 Google Documentation on Commons Layouts和这个What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?的答案, ViewGroup作为 LinearLayout , RelativeLayout , AbsoluteLayout (已废弃)TableLayout等可以显示 View :

  1. LinearLayout:“一个一个地显示 View ”
  2. RelativeLayout:“显示关于另一个 View 的 View ”
  3. TableLayout:“在表中显示 View ”

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

"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

好的,但是为什么我需要这个 Fragment ? (对比 LinearLayout 或 )

Google Documentation of FrameLayout说:

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

FrameLayout将承载一个布局并且它愿意这样做。而其余的 ViewGroup只是显示 View 。你可以做一个Fragment总共ViewGroup s (我对此进行了测试,这对我来说是一个惊喜) 但这不是执行此操作的正确方法。 FrameLayout是:

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

如果您使用 <fragment .../> 创建布局,您的 fragment 将不会被另一个 fragment 替换,因为它已显示,并且在 View 上“附加”了它的 ID。要替换 fragment ,您需要托管它:“通过将 fragment 封装在 FrameLayout 中,您可以仅替换细节”(参见 this answer)。

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

希望这会有所帮助。

注意:如果有人想编辑这个答案,因为它没有解释或解释得不好,她/他可以衷心同意。

关于java - Android: remove() Fragment--> add() new Fragment of same class again ->onCreateView and onActivityCreated 没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com