I’m trying to detect the change of the orientation. I’ve read the Documentation but still can’t figure out How can i use addOrientationChangeListener
correctly in my code below:
export default class VideoScreen extends Component {
constructor(props) {
super(props);
this.state = {
orientation: 1,
};
}
async componentDidMount() {
await this.detectOrientation();
this.subscription = ScreenOrientation.addOrientationChangeListener(this.onOrientationChange);
}
async componentWillUnmount() {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT);
ScreenOrientation.removeOrientationChangeListener(this.subscription);
}
onOrientationChange = async (orientation) => {
console.log('orientation changed');
if (orientation === 3 || orientation === 4) {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE);
} else {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT);
}
this.setState({ orientation });
};
detectOrientation= async () => {
let orientation = await ScreenOrientation.getOrientationAsync();
const screen = Dimensions.get('screen');
if (orientation === 0) {
orientation = screen.width > screen.height ? ScreenOrientation.Orientation.LANDSCAPE : ScreenOrientation.Orientation.PORTRAIT;
}
this.setState({ orientation });
console.log(orientation);
};
render() {
const { route } = this.props;
const { videoUri } = route.params;
if (!videoUri) {
NavigationHelper.back();
}
return (
<ScrollView style={styles.container}>
<Video
source={{ uri: videoUri }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode={Video.RESIZE_MODE_CONTAIN}
shouldPlay
isLooping
useNativeControls
style={{ width: 300, height: 300, alignSelf: 'center' }}
orientationChange={this.onOrientationChange}
/>
</ScrollView>
);
}
}