子母畫面 (PiP) 是一種特殊的多視窗模式,主要用於影片播放。這個模式可讓使用者透過固定在畫面角落的小視窗觀看影片,同時繼續在主要畫面使用應用程式或瀏覽內容。
子母畫面會利用 Android 7.0 的多視窗 API 提供固定的影片重疊視窗。如要為應用程式新增子母畫面功能,您必須登錄活動、視需要將活動切換至子母畫面模式,並確認活動處於子母畫面模式時,UI 元素皆為隱藏狀態且影片會繼續播放。
Implement PiP with Jetpack
Use the Jetpack Picture-in-Picture library to implement picture-in-picture experience as it streamlines integration and reduces common in-app issues. Refer to our platform sample app to see an example of its usage. However, if you prefer to implement PiP using the platform APIs, refer to the following documentation.
在子母畫面模式下處理 UI
進入子母畫面模式時,應用程式的整個 UI 都會進入子母畫面視窗,除非您指定 UI 在子母畫面模式內外的顯示方式。
首先,您需要知道應用程式是否處於子母畫面模式。您可以使用 OnPictureInPictureModeChangedProvider 達成這個目的。以下程式碼會告知應用程式是否處於子母畫面模式。
@Composable fun rememberIsInPipMode(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val activity = LocalContext.current.findActivity() var pipMode by remember { mutableStateOf(activity.isInPictureInPictureMode) } DisposableEffect(activity) { val observer = Consumer<PictureInPictureModeChangedInfo> { info -> pipMode = info.isInPictureInPictureMode } activity.addOnPictureInPictureModeChangedListener( observer ) onDispose { activity.removeOnPictureInPictureModeChangedListener(observer) } } return pipMode } else { return false } }
現在,您可以使用 rememberIsInPipMode() 切換應用程式進入子母畫面模式時要顯示的 UI 元素:
val inPipMode = rememberIsInPipMode() Column(modifier = modifier) { // This text will only show up when the app is not in PiP mode if (!inPipMode) { Text( text = "Picture in Picture", ) } VideoPlayer() }