如何锁定设备竖屏,使得窗口不随屏幕旋转?

如何锁定设备竖屏,使得窗口不随屏幕旋转

阅读 487
1 个回答

解决措施

采用窗口的setPreferredOrientation方法可以实现该效果,将orientation参数设置为window.Orientation.PORTRAIT时,可锁定屏幕为竖屏。

代码示例

import { BusinessError } from '@kit.BasicServicesKit'; 
import { window } from '@kit.ArkUI'; 
 
//1.获取窗口实例对象,新建窗口使用createWindow方法,获取已有的窗口使用findWindow方法 
let windowClass: window.Window | undefined = undefined; 
let config: window.Configuration = { 
  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: BusinessError)=>{ 
    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.AUTO_ROTATION; 
try { 
  let windowClass: window.Window = window.findWindow("test"); 
  windowClass.setPreferredOrientation(orientation, (err: BusinessError) => { 
    const errCode: number = err.code; 
    if (errCode) { 
      console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); 
      return; 
    } 
    console.info('Succeeded in setting window orientation.'); 
  }); 
} catch (exception) { 
  console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); 
}

参考链接

window.Orientation

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进