gpt4 book ai didi

android - 具有方向更改的单 Activity 应用程序中的 YouTubePlayerSupportFragment

转载 作者:可可西里 更新时间:2023-11-01 19:07:38 24 4
gpt4 key购买 nike

我试图解决这个问题,通过互联网搜索,没有找到真正的答案。

我正在开发一款需要 YouTube 播放器的应用。这个播放器是YouTubePlayerSupportFragment因为它在支持 fragment 中(所以它也是嵌套的)。初始设置后,我意识到每当我旋转手机时,视频就会停止播放,必须重新启动。这显然不是我想要的。

然后我找到了一些 SO 答案 ( like this ),其中人们说 Activity 需要处理配置更改,所以我将 android:configChanges="keyboardHidden|orientation|screenSize" 添加到 list 中的 Activity 。这解决了问题,视频现在即使在方向改变时也能继续播放,而且全屏旋转看起来并不难看。太棒了,我说,只是意识到这把应用程序的其他部分搞得一团糟,因为配置现在正在更新所有 View 都就位后。这意味着如果我的手机处于纵向模式并且我将其旋转为横向,所使用的布局仍将是纵向布局。

我找到了解决方案,建议在 Activity 的 onConfigurationChanged(...) 中调用 setContentView(...) 并在 fragment 中重新填充 View ,但这似乎这是一个相当麻烦的解决方案,如果不是可怕的解决方案,因为它不仅仅是我需要的简单内容设置,还需要保留 fragment (例如 RecyclerView 中的滚动位置)。内置的 setRetainInstance(true) 在这种情况下不起作用,因为 View 将被重新创建,但是当 onCreateView(...) 正在被调用。

如果我可以在用户仅在该屏幕( fragment )上但在其他任何地方保留 Activity 重新创建时捕获 configChanges 事件,那就太好了。

不建议使用更多 Activity,由于 UI/UX 原因,我不能为此屏幕和应用程序的其余部分使用单独的 Activity。

最佳答案

根据 this YouTube Android Player API 指南

It is encouraged that you handle configuration changes caused by orientation in your activity manually, to avoid recreating this fragment's view every time the configuration changes. For the best user experience, you should also manually handle the fullscreen event by changing the layout of your activity.(See the second approch)

由于您已经在自行处理配置更改,因此我可以看到您的问题有两种可能的解决方案。

  1. 设置setFullscreenControlFlags (到您的 YouTubePlayer 对象)到 FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE (这将导致播放器在设备进入横向时自动进入全屏。)结合 FULLSCREEN_FLAG_CONTROL_ORIENTATION (启用方向的自动控制。)标记。

Note that this flag should only be set if your activity is locked in portrait (and is specified as such in the manifest).

The flag is useful if you don't have a landscape layout for your activity, but would like to enable landscape orientation solely for fullscreen video watching.

  1. 这种方法可能会解决您的问题,正如我上面提到的,官方文档也建议使用这种方法。在 setFullscreenControlFlags 方法中设置 FULLSCREEN_FLAG_CUSTOM_LAYOUT ,它会禁用默认的全屏布局处理程序,使您能够手动控制到全屏布局的转换。除了使您能够实现自定义全屏布局外,此选项还具有避免在默认全屏行为中发生重新缓冲的优势。

An application implementing custom fullscreen behavior should ensure two things

That the player's view takes up the whole available space of application's window whenever onFullscreen(boolean) is called. That the activity is not recreated when the orientation changes to landscape. To achieve this for an activity that supports portrait, you need to specify that your activity handles some configuration changes on its own in your application's manifest, including orientation, keyboardHidden and screenSize.

参见 here关于如何使用这个标志。

根据第一个link我分享过,第二种方法将避免每次配置更改时都重新创建 fragment 的 View 。此外,您不需要在 onConfigurationChanged(...) 中调用 setContentView(...)

希望对您有所帮助。

关于android - 具有方向更改的单 Activity 应用程序中的 YouTubePlayerSupportFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363935/

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