Android端Expo Video原生控件全屏旋转功能失效求助
解决Android端Expo Video全屏自动旋转问题
Android系统在应用全局锁定竖屏后,不会主动响应视频控件的旋转请求,得通过动态切换屏幕方向权限来实现和iOS一致的效果,具体步骤如下:
1. 安装依赖
先安装expo-screen-orientation库,用于动态控制屏幕方向:
npx expo install expo-screen-orientation
2. 配置app.json
在app.json的expo字段中添加屏幕方向权限和Android相关配置:
{ "expo": { // 保留原有配置 "orientation": "portrait", "android": { "permissions": ["android.permission.CHANGE_CONFIGURATION"], "config": { // 保留原有配置 } }, "plugins": [ [ "expo-screen-orientation", { "initialOrientation": "PORTRAIT" } ] ] } }
3. 修改VideoPlayer组件
通过监听视频全屏状态,动态切换屏幕方向,退出全屏时恢复竖屏锁定:
import { View } from 'react-native' import React, { useEffect, useRef } from 'react' import { Video } from 'expo-av' import * as ScreenOrientation from 'expo-screen-orientation' export function VideoPlayer(props) { const { videoURL } = props; const videoRef = useRef(null); const originalOrientation = useRef(null); // 组件挂载时记录初始屏幕方向 useEffect(() => { const getOriginalOrientation = async () => { originalOrientation.current = await ScreenOrientation.getOrientationAsync(); }; getOriginalOrientation(); // 组件卸载时恢复初始方向 return () => { if (originalOrientation.current) { ScreenOrientation.lockAsync(originalOrientation.current); } }; }, []); // 处理全屏状态变化 const handleFullscreenUpdate = async (status) => { if (status.fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_DID_PRESENT_FULLSCREEN) { // 进入全屏,解锁屏幕方向允许自动旋转 await ScreenOrientation.unlockAsync(); } else if (status.fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS_FULLSCREEN) { // 退出全屏,重新锁定竖屏 await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT); } }; return ( <View> <Video ref={videoRef} source={{ uri: videoURL }} style={{ width: '100%', aspectRatio: 16 / 9, alignSelf: 'center', borderRadius: 10, backgroundColor: "black" }} useNativeControls resizeMode="contain" hideControlsTimeoutMillis={5000} onFullscreenUpdate={handleFullscreenUpdate} /> </View> ) }
关键说明
- 通过
onFullscreenUpdate监听视频全屏状态,进入全屏时解锁方向权限,退出时恢复竖屏锁定; - 组件挂载时记录初始方向,卸载时恢复,避免影响应用其他页面的方向设置;
- Android需添加
CHANGE_CONFIGURATION权限,确保应用具备修改屏幕方向的权限。
内容的提问来源于stack exchange,提问作者Juan Truncon
相关产品推荐
相关产品推荐

