OpenHarmony开发者论坛

标题: 如何锁定设备竖屏,使得窗口不随屏幕旋转 [打印本页]

作者: 汐之蓝    时间: 2023-10-31 11:25
标题: 如何锁定设备竖屏,使得窗口不随屏幕旋转
[md]【问题描述】

设备切换竖屏,排版全乱了,不能进入程序后锁定竖屏,窗口不能随意旋转?使用到哪些API呢?

【运行环境】

硬件:

ROM版本:OpenHarmony 3.2 Beta5

DevEvoStudio版本:

SDK版本:API 9

[/md]
作者: westinyang    时间: 2023-10-31 11:48
标题: 如何锁定设备竖屏,使得窗口不随屏幕旋转
[md]```js
// 获取所有的屏幕
let screenClass = null;
screen.getAllScreens((err, data) => {
    if (err.code) {
        console.error('Failed to get all screens. Cause:  ' + JSON.stringify(err));
        return;
    }
    console.info('Succeeded in getting all screens. Data:' + JSON.stringify(data));
    screenClass = data[0];
   
    // 设置屏幕方向 VERTICAL HORIZONTAL
    try {
        screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => {
            if (err.code) {
                console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in setting the vertical orientation. data: ' + JSON.stringify(data));
        });
    } catch (exception) {
        console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception));
    };
});
```

AIP详细说明可参考:[@ohos.screen (屏幕) (openharmony.cn)](https://docs.openharmony.cn/page ... s-screen.md/#screen)

[/md]
作者: HmD    时间: 2023-11-8 14:12
[md]采用窗口的setPreferredOrientation方法可以实现该效果,将orientation参数设置为window.Orientation.PORTRAIT时,可锁定屏幕为竖屏。

```
import window from "@ohos.window";
//1.获取窗口实例对象,新建窗口使用createWindow方法,获取已有的窗口使用findWindow方法
let windowClass = null;
let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context};
try {
    let promise = window.createWindow(config);
    promise.then((data)=> {
        windowClass = data;
        console.info('Succeeded in creating the window. Data:' + JSON.stringify(data));
    }).catch((err)=>{
        console.error('Failed to create the Window. Cause:' + JSON.stringify(err));
    });} catch (exception) {
    console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));
}
//2.窗口实例使用setPreferredOrientation方法,设置窗口的显示方向,PROTRAIT为固定竖屏,其他方向可参照参考链接
let orientation = window.Orientation.PORTRAIT;
if (windowClass) {
    windowClass.setPreferredOrientation(orientation, (err) => {
        if (err.code) {
            console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err));
            return;
        }
        console.info('Succeeded in setting window orientation.');
}
```

[/md]




欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/) Powered by Discuz! X3.5