首页 > 其他分享 >OpenHarmony如何切换横竖屏?

OpenHarmony如何切换横竖屏?

时间:2023-01-18 11:22:34浏览次数:51  
标签:OpenHarmony console orientation err 横竖 window 切换 context portrait

 前言

在日常开发中,大多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模型下获取context
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%')
  }
}
 

  

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
@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(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()),大家可以在此基础上利用生命周期的回调,在合适的地方完成对应的操作。

 

标签:OpenHarmony,console,orientation,err,横竖,window,切换,context,portrait
From: https://www.cnblogs.com/openharmony/p/17059455.html

相关文章

  • 一个解决视频切换花屏的方案
    问题:最近在开发一个项目,该项目需要在主被叫视频通话过程中对主叫播放视频彩铃,当视频彩铃播放完成后,再切回到主被叫视频通话。开发完成后,进行测试中发现存在一个问题。......
  • 从log4j切换到logback后项目无法启动
    1、背景有个旧项目之前使用的是log4j2来打印日志的,因为某些原因,同事想换成logback。换成logback改动也很简单,大致就一下2步:删除log4j2.xml配置,新增logback.xml配置。......
  • 20.Selenium【iframe切换】切换页面的iframe、handlers
    一、前言在做web自动化的时候,我们往往会遇到两种切换:iframe、handler。iframe表示在主html上嵌入的子html页面(说人话就是一个页面中套着一个或多个页面);handler表示一个新......
  • postgresql14主备流复制状态切换
    pg12开始新增了一个pg_promote()函数,可以通过SQL命令激活备库。pg_promote()语法pg_promote(waitbooleanDEFAULTtrue,wait_secondsintegerDEFAULT60)两个参数:w......
  • vue-cli脚手架3.0以上切换到3.0以下版本
    vue-cli脚手架3.0前后版本切换3.0以上—>3.0以下:vue-V //查询版本号npmuninstall-g@vue/cli//卸载npminstall-gvue-cli//安装2.9.6npminpm-gnpmivu......
  • 在vue中使用Echarts绘制叠堆折线面积图(可切换叠堆柱状图)
    (文章目录)效果我这里用的框架是Element+vue,将可视化图表用card卡片包起来,这个叠堆折线面积图主要实现的功能有:1.默认进入时看到的是叠堆折线面积图,在点击对应的元素切......
  • fineReport切换数据源
    fineReport切换数据源:1.配置数据连接2.报表内选中......
  • WindTerm快速切换标签页
    默认使用Alt+[和Alt+]进行切换,如需修改常规的Ctrl+Tab进行如下操作找到快捷键配置文件WindTerm_2.6.0\global下的wind.keymaps并打开。如果找不到的话,用everything搜......
  • OpenHarmony开发环境快速搭建(无需命令行)
    一.搭建Windows环境在嵌入式开发中,很多开发者习惯于使用Windows进行代码的编辑,比如使用Windows的VisualStudioCode进行OpenHarmony代码的开发。但当前阶段,大部分的开发板......
  • 如何使用滑块实现切换图片功能?
    效果展示:前置准备:链接好四张图片的组件切换器具体步骤:添加滑块组件创建组件切换器触发器创建执行其他触发器创建值改变触发器步骤分解:添加滑块组件添加滑块组件配......