前言
在日常开发中,大多 APP 可能根据实际情况直接将 APP 的界面方向固定,或竖屏或横屏。但在使用过程中,我们还是会遇到横竖屏切换的功能需求,可能是通过物理重力感应触发,也有可能是用户手动触发。所以本文主要带大家了解在 OpenAtom OpenHarmony(以下简称“OpenHarmony”)应用开发的过程中,如何在 Stage 模型和 FA 模型下使用对应的接口去完成横竖屏的切换。
本文中 OpenHarmony 版本为 3.2 Beta4,API 版本为 9。开发板为 DAYU200。
FA 模型
FA 模型下,setDisplayOrientation 和 setDisplayOrientation 是切换横竖屏的接口。文档:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7
context.setDisplayOrientation
setDisplayOrientation(orientation:bundle.DisplayOrientation, callback: AsyncCallback<void>): void
设置当前能力的显示方向(callback 形式)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
示例:
 import featureAbility from '@ohos.ability.featureAbility';import bundle from '@ohos.bundle';//FA模型下获取contextvar context = featureAbility.getContext();var orientation = bundle.DisplayOrientation.UNSPECIFIED;context.setDisplayOrientation(orientation, (err) => {    console.info("setDisplayOrientation err: " + JSON.stringify(err));});
       复制代码
 
完整代码
        import bundle from '@ohos.bundle';import featureAbility from '@ohos.ability.featureAbility';@Entry@Componentstruct Index {  @State message: string = '横竖屏切换 '  @State portrait: boolean = true
  build() {    Row() {      Column() {        Text(this.message)          .fontSize(30)          .fontWeight(FontWeight.Bold).onClick(() => {          var context = featureAbility.getContext();          if (this.portrait) {
            // 横屏            var orientation = bundle.DisplayOrientation.LANDSCAPE;            context.setDisplayOrientation(orientation, (err) => {              this.portrait = !this.portrait              console.info("setDisplayOrientation err: " + JSON.stringify(err));            });          } else {            //竖屏            var orientation = bundle.DisplayOrientation.PORTRAIT;            context.setDisplayOrientation(orientation, (err) => {              this.portrait = !this.portrait              console.info("setDisplayOrientation err: " + JSON.stringify(err));            });                }        })      }      .width('100%')    }    .height('100%')  }}
       复制代码
 
Stage 模型
从 API 9 开始,可以使用 setPreferredOrientation 来切换横竖屏。
文档:
https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-window.md#setpreferredorientation9
在 Stage 模型中,使用到的主要是 Window(窗口)。在设置横竖屏切换的时候,需要先使用 getLastWindow()、createWindow()、findWindow()中的任一方法获取到 Window 实例,再通过此实例调用对应的方法,本文使用的是 getLastWindow。
Window.getLastWindow
getLastWindow(ctx: BaseContext): Promise<Window>
获取当前应用内最后显示的窗口,使用 Promise 异步回调。
系统能力:SystemCapability.WindowManager.WindowManager.Core
参数:
返回值:
错误码:以下错误码的详细介绍请参见窗口错误码。
 let windowClass = null;try {    let promise = window.getLastWindow(this.context);    promise.then((data)=> {        windowClass = data;        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));    }).catch((err)=>{        console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));    });} catch (exception) {    console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));}
       复制代码
 
然后就可以使用 setPreferredOrientation 属性。
setPreferredOrientation
setPreferredOrientation(orientation: Orientation): Promise<void>
设置窗口的显示方向属性,使用 Promise 异步回调。
系统能力:SystemCapability.WindowManager.WindowManager.Core
参数:
返回值:
错误码:以下错误码的详细介绍请参见窗口错误码。
 let orientation = window.Orientation.AUTO_ROTATION;try {    let promise = windowClass.setPreferredOrientation(orientation);    promise.then(()=> {        console.info('Succeeded in setting the window orientation.');    }).catch((err)=>{        console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err));    });} catch (exception) {    console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception));}
       复制代码
 
完整代码
 import Window from '@ohos.window'import common from '@ohos.app.ability.common';@Entry@Componentstruct ArkUIClubTest {  private portrait: boolean = true  build() {    Stack() {      Button("横竖屏切换")        .onClick(() => {          this.changeOrientation()        })    }    .width('100%')    .height('100%')  }  private changeOrientation() {    let windowClass = null;    //获取上下文    //var context = getContext(this) as any    // 获取上下文,使用common模块     var context =   getContext(this) as common.UIAbilityContext;    let promise = Window.getLastWindow(context);    promise.then((data) => {      windowClass = data;      if (this.portrait) {        //切换成横屏        let orientation = Window.Orientation.LANDSCAPE;        windowClass.setPreferredOrientation(orientation, (err) => {       });        this.portrait = !this.portrait        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));      }      else {        //切换成竖屏        let orientation = Window.Orientation.PORTRAIT;        windowClass.setPreferredOrientation(orientation, (err) => {        });        this.portrait = !this.portrait        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));      }    }).catch((err) => {      console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));    });  }}
       复制代码
 
总结
本文带大家使用对应的接口,在 Stage 模型和 FA 模型下完成了横竖屏的切换。其中还涉及到了上下文的获取:Stage 模型用(getContext(this) as any),FA 模型(featureAbility.getContext()),大家可以在此基础上利用生命周期的回调,在合适的地方完成对应的操作。
评论