打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
OpenHarmony/HarmonyOS如何切换横竖屏?

OpenHarmony/HarmonyOS如何切换横竖屏?

作者:坚果,公众号:”大前端之旅“,哔哩哔哩,OpenHarmony布道师,OpenHarmony校源行开源大使,电子发烧友鸿蒙MVP,51CTO博客专家博主,阿里云博客专家。

本文中,FA模型我用的HarmonyOS3的手机,API版本为8

Stage模型我用的OpenHarmony3.2,API版本为9

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.setDisplayOrientation7+

setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback): void

设置当前能力的显示方向(callback形式)。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名类型必填说明
orientationbundle.DisplayOrientation指示当前能力的新方向。
callbackAsyncCallback表示屏幕显示方向。

示例:

import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle';
var 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
@Component
struct 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%')
  }
}

上面这样写太乱了,我们可以封装一下

import bundle from '@ohos.bundle';
import featureAbility from '@ohos.ability.featureAbility';


@Entry
@Component
struct Index {
  @State message: string = '横竖屏切换 '
  @State portrait: boolean = true

  private changePortrait() {
    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));
      });

    }

  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(() => {
this.changePortrait()
        })
      }
      .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

获取当前应用内最后显示的窗口,使用Promise异步回调。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名类型必填说明
ctxBaseContext当前应用上下文信息。FA模型的Context定义见Context。Stage模型的Context定义见Context。

返回值:

类型说明
Promise<Window>Promise对象。返回当前应用内最后显示的窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码。

错误码ID错误信息
1300002This window state is abnormal.
1300006This window context is abnormal.
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

设置窗口的显示方向属性,使用Promise异步回调。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名类型必填说明
OrientationOrientation窗口显示方向的属性。

返回值:

类型说明
Promise无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见窗口错误码。

错误码ID错误信息
1300002This window state is abnormal.

示例:

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'

@Entry
@Component
struct ArkUIClubTest {
  private portrait: boolean = true

  build() {
    Stack() {
      Button("横竖屏切换")
        .onClick(() => {
          this.changeOrientation()
        })
    }
    .width('100%')
    .height('100%')
  }

  private changeOrientation() {
    let windowClass = null;
    var context = getContext(thisas any
    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));
    });


  }
}

@system.app (应用上下文)使用

HarmonyOS/OpenHarmony 双击返回与退出App

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
apicloud 保存图片和视频到系统相册
软件开发请求对象为空值
开发教程|如何使用APICloud的AVM框架开发一个应用?
鸿蒙上实现微信的聊天功能!
【实战】小程序云开发之云函数开发
转义字符(\)对JavaScript中JSON.parse的影响
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服