繁体   English   中英

在FrameLayout中的视图(膨胀片段)之间切换时出现问题

[英]issue while switching between views (inflated fragments) in FrameLayout

我的问题如下:

我有一个具有一个主要活动的应用程序,其中有一个frameLayout容器(containerViewId),可用于在菜单导航器选择时显示/填充不同的片段。

我实际上是在活动onCreate()上创建所有片段对象并将其添加到frameLayout的:

伪代码:

//在主要活动中onCreate()

Fragment1 fragment_1 = new Fragment1();

Fragment2 fragment_2 = new Fragment2()

Fragment3 fragment_3 = new Fragment3()

fragmentTransaction.add(containerViewId, fragment_1, "frag_1");
fragmentTransaction.add(containerViewId, fragment_2, "frag_2");
fragmentTransaction.add(containerViewId, fragment_3, "frag_3");

// hide fragments 2&3, so only fragment_1 is showed

fragmentTransaction.hide(fragment_2);

fragmentTransaction.hide(fragment_3);

.commit()..

现在,当用户从导航视图中选择特定选项时,我只是隐藏当前显示的片段,并按如下所示显示所需的片段(例如,从fragment_1切换到fragment_2):

 fragmentTransaction.hide(fragment_1);

 fragmentTransaction.show(fragment_2);

 fragmentTransaction.commit();

一切都按预期工作(片段已成功切换),但是我有时观察到一段时间(当我将我的应用程序从后台移到前端时)之前的片段会突然显示/重叠在一起(即使我始终隐藏当前片段并显示下一个)

我想念什么吗? 为什么突然显示我以前的观点?

谢谢 :-)

您需要替换而不是堆叠片段。 如果您希望能够导航回到上一个片段,请使用addToBackStack

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

fragmentmanager上有一些方法可以从backstack中获取或弹出先前的片段:popBackStack(),getBackStackEntryAt(int index)等。

更新

方法popBackStack将弹出堆栈的顶部。 Backstack包含BackStackEntries Backstack条目仅包含片段的某些参考字段。 您应该将片段作为变量包含在包含的类中,以便可以替换它们。 请注意,您应始终实施适当的生命周期管理,因为在Android中,如果您将数据放在后台,则永远不会确保数据仍在内存中。

这是有关活动生命周期的一些信息,但是对于片段来说,它们基本上是相同的:

在先前销毁活动之后重新创建活动之后,可以从捆绑包中恢复系统通过活动的保存状态。 onCreate()和onRestoreInstanceState()回调方法都接收包含实例状态信息的同一个Bundle。

由于onCreate()方法是系统是创建活动的新实例还是重新创建活动的实例而调用的,因此在尝试读取状态Bundle之前,必须检查其状态是否为null。 如果为空,则系统将创建活动的新实例,而不是还原先前被破坏的活动。

有关片段生命周期的一些官方文档: https : //developer.android.com/guide/components/fragments.html#Lifecycle

把事情简单化。 做这样的事情-

    Fragment1 fragment_1 = new Fragment1();
    Fragment2 fragment_2 = new Fragment2();
    Fragment3 fragment_3 = new Fragment3();

    fragmentTransaction.replace(containerViewId, fragment_1, "frag_1"); //when you want show fragment 1
    fragmentTransaction.commit();

//similarly just replace with fragment2 and fragment 3 when you want to show them respectively.The trick is to replace (which internally removes all previously added fragments before adding the current fragment, thus no overlapping issues)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM