应用设置屏幕自动旋转:在模块配置文件module.json5中给EntryAbility设置"orientation": “auto_rotation_restricted”,再打开手机自动旋转即可。应用中通过window.getLastWindow 获取window实例–>用setPreferredOrientation设置窗口显示方向的属性。通过diplay.on可以监听屏幕状态改变。点击设置了具体方向后,再加上传感器模式判断屏幕方向。demo如下:import window from '@ohos.window'; import display from '@ohos.display'; const TAG = 'foo' const ORIENTATION: Array<string> = ['垂直','平', '反向垂直', '反向水平'] @Entry @Component struct Index { @State rotation: number = 0 @State message: string = ORIENTATION[this.rotation] @Watch('setWindowLayOut') @State isLandscape: boolean = false;// 是否横屏状态 aboutToAppear() { this.setOrientation(1) let callback = async () => { let d = await display.getDefaultDisplaySync() this.rotation = d.rotation this.message = ORIENTATION[this.rotation] console.info(TAG, JSON.stringify(d)) } try { display.on("change", callback);//监听屏幕状态改变 } catch (exception) { console.error(TAG, 'Failed to register callback. Code: ' + JSON.stringify(exception)); } } setOrientation(type : number) { try { window.getLastWindow(getContext(this), (err, data) => { //获取window实例 if (err.code) { console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(err)); return; } let windowClass = data; console.info(TAG, 'Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); let orientation : number; if (type === 1) { orientation = window.Orientation.AUTO_ROTATION; //设置窗口方向为传感器自动旋转模式。 } else { orientation = window.Orientation.UNSPECIFIED; //设置窗口方向为传感器锁定。 } try { windowClass.setPreferredOrientation(orientation, (err) => { if (err.code) { console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(err)); return; } console.info(TAG, 'Succeeded in setting window orientation.'); }); } catch (exception) { console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(exception)); } ; }); } catch (exception) { console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); } ; } setWindowLayOut() { // 调用该接口手动改变设备横竖屏状态(设置全屏模式,先强制横屏,再加上传感器模式) window.getLastWindow(getContext(this)).then((windowClass) => { if (this.isLandscape) { console.log('设置屏幕横屏') windowClass.setPreferredOrientation(window.Orientation.AUTO_ROTATION_LANDSCAPE); } else { console.log('设置屏幕竖屏') windowClass.setPreferredOrientation(window.Orientation.AUTO_ROTATION_PORTRAIT); } }); } build() { Row() { Column() { Text(`${this.rotation}`).fontSize(25) Text(`${this.message}`).fontSize(25) Button('全屏') .width(140) .onClick(() => { this.isLandscape = !this.isLandscape; // 设置横屏 }); } .width("100%") } .height('100%') } }
应用设置屏幕自动旋转:在模块配置文件module.json5中给EntryAbility设置"orientation": “auto_rotation_restricted”,再打开手机自动旋转即可。应用中通过window.getLastWindow 获取window实例–>用setPreferredOrientation设置窗口显示方向的属性。通过diplay.on可以监听屏幕状态改变。点击设置了具体方向后,再加上传感器模式判断屏幕方向。demo如下: