gpt4 book ai didi

android - 即使从横向旋转到垂直,细节 fragment 也会重新开始。 (主从流程)

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:53 24 4
gpt4 key购买 nike

在一个 Activity 中,我们称它为 MasterActivity,我只想在横向模式下加载带有媒体播放的细节 fragment 。媒体在准备就绪时自动启动。

主从流程设置:我有两个 xml,activity_master 和 activity_master.xml(land)。 id 为“detail_container”的容器 View 仅在横向 xml 中。带有细节容器的横向 xml 的目的是在宽度 >900 的同一屏幕上同时显示主要细节。

在 onCreate() 中,这是我通过检查“detail_container”的存在来确定屏幕方向的方式,如下所示:

if (findViewById(R.id.detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
mTwoPane = true;
}

并且在 Activity 的 OnCreate() 中,我有以下代码在 Activity 处于双 Pane 模式(大屏幕布局上的横向)时自动加载 fragment

if (mTwoPane) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_container,
someFragment.newInstance(MEDIA_URI))
.commit();
}

问题:

当我开始垂直 Activity 时, fragment 未加载(预期)。

当我开始横向 Activity 时, fragment 被加载(预期)。

在屏幕旋转时, fragment 被销毁(预期,播放停止,资源仅在 onDestory() 中释放);

问题是当我在横向开始 Activity 但将其旋转到垂直时, fragment 重新启动,并且媒体播放再次开始(意外)。

我的目标:我希望当设备在大屏幕设备上处于横向时自动加载 fragment ,在设备旋转时 fragment 不应再次加载。

编辑:在垂直模式下, fragment 不应自动加载,用户会点击主 Activity ,打开详情 Activity ,详情 Activity 将承载详情 fragment 。

我该怎么办?提前致谢

额外信息:测试物理设备是运行 Android 5.0 API 21 的 7' 平板电脑,该问题也存在于模拟器中。

最佳答案

当发生配置更改时,Android 将确保重新创建附加到 Activity 的所有 fragment 并重新附加回新 Activity 的 FragmentManager;这与 fragment 是否考虑了 setRetainInstance(...) 是分开的。

所以看起来你想要做的是反对 fragment 的自动重新附加。我对此也很好奇,所以我深入研究了 FragmentActivity.onCreate(...)FragmentManager 但我找不到任何允许开发人员禁止此自动过程的内容。但是,您可以通过在代码中执行以下操作来使用 FragmentTransaction 解决该过程:

FragmentManager manager = getSupportFragmentManager();

if (mTwoPane) {
// set up your two pane
manager.beginTransaction()
.replace(R.id.detail_container,
someFragment.newInstance(MEDIA_URI),
someFragment.TAG)
.commit();
} else {
// this is not two pane, so remove the fragment if it is attached
Fragment detail = manager.findFragmentByTag(someFragment.TAG);
if (detail != null) {
manager.beginTransaction()
.remove(detail)
.commit();
}
}

关于android - 即使从横向旋转到垂直,细节 fragment 也会重新开始。 (主从流程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46313949/

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