鸿蒙应用实现横竖屏切换有几种方式?注意事项有什么?

鸿蒙应用实现横竖屏切换有几种方式?注意事项有什么?

一、结论

目前共还有两种方式实现应用的横竖屏切换。

1、静态配置

2、动态调用接口

注意事项:

1、设置主窗口的显示方向属性。仅在支持跟随sensor旋转的设备上生效,子窗口调用后不生效。

2、module.json5中。"orientation": "auto_rotation"随传感器旋转 需要在系统下滑菜单中,放开自动锁定状态才可生效。

3、退出逻辑的闭环。例如只有进入当前页面需要某种横竖屏状态,推出该界面时,需要将状态重置回原先。

二、代码实现和详细解释

1、静态配置:

在module.json5添加属性"orientation" 具体的值。数值详情参见:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-window-e#orientation9

常用配置值:

portrait:仅竖屏

landscape:仅横屏

auto_rotation_restricted:跟随传感器旋转,受系统旋转锁定控制

follow_desktop:跟随桌面的旋转模式。适配不同设备形态(如折叠机展开时自动横屏)

typescript 复制代码
"abilities": [ 
  { 
    "name": "EntryAbility", 
    "srcEntry": "./ets/entryability/EntryAbility.ets", 
    "description": "$string:EntryAbility_desc", 
    "icon": "$media:icon", 
    "label": "$string:EntryAbility_label", 
    "startWindowIcon": "$media:startIcon", 
    "startWindowBackground": "$color:start_window_background", 
    "exported": true, 
    "skills": [ 
      { 
        "entities": [ 
          "entity.system.home" 
        ], 
        "actions": [ 
          "action.system.home" 
        ] 
      } 
    ], 
    "orientation": "auto_rotation", // 随传感器旋转 
  } 
]

2、调用接口手动切换:

核心代码是调用窗口的 setPreferredOrientation方法,动态修改窗口方向。所以首先我们要获取主窗口。

不建议使用window.getLastWindow这种方式,获取当前的窗口。因为该接口是异步,状态获取不稳定,并且有性能损耗。

typescript 复制代码
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // 挂载globalThis上,可以当全局对象使用。当然此处实现方式因人而异,你可以放在单例里,或者APPstore中等等. 目前api20已经不推荐globalThis该方式
    globalThis.windowClass = windowStage.getMainWindowSync();
		// 一般是缓存当前舞台,也就是windowStage,可以在任意逻辑类或者UI类中,进行舞台,窗口,或者上下文的获取。较为灵活。
    
    windowStage.loadContent('pages/RotationTestPage', (err) => {
      if (err.code) {
        return;
      }
    });
  }
}

之后在需要调用横竖屏切换的页面或者逻辑中调用,我这里用按钮触发举例:

RotationTestPage.ets

typescript 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

@Entry
@Component
struct RotationTestPage {
  private TAG: string = "RotationTestPage";

  onClickRotation = ()=>{
  	// 设置横竖屏状态
    let orientation = window.Orientation.LANDSCAPE;
    try{
      globalThis.windowClass.setPreferredOrientation(orientation, (err: BusinessError) => {
        if(err.code){
          console.error(this.TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(err));
          return;
        }
        console.info(this.TAG,'Succeeded in setting window orientation.');
      });
    }catch (exception) {
      console.error(this.TAG,'Failed to set window orientation. Cause: ' + JSON.stringify(exception));
    }
  }

  build() {
    RelativeContainer() {
      Text("点击切换为横屏")
        .id('RotationTestPageHelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(this.onClickRotation)
    }
    .height('100%')
    .width('100%')
  }
}

三、如何监听屏幕旋转

这在处理屏幕旋转逻辑中,经常也会用到。使用媒体查询接口监听屏幕旋转,代码如下所示:

typescript 复制代码
import { mediaquery } from '@kit.ArkUI'; 
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // 监听横屏事件 
function onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) { 
  if (mediaQueryResult.matches) { 
   // do something here 
  } else { 
   // do something here 
  } 
} 
listener.on('change', onPortrait) // 注册回调 
listener.off('change', onPortrait) // 去注册回调

引用资料地址:

官方文档,横竖屏切换内容:

https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-landscape-and-portrait-development#section289353110179

横竖屏切换配置,数值的具体参数值介绍:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/module-configuration-file#abilities标签

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-window-e#orientation9

相关推荐
国服第二切图仔2 小时前
Electron for 鸿蒙PC项目实战案例之简单统计组件
javascript·electron·harmonyos
奔跑的露西ly2 小时前
【HarmonyOS NEXT】组件化与模块化的理解
华为·harmonyos
晚霞的不甘2 小时前
Flutter 与开源鸿蒙(OpenHarmony)深度集成:从插件开发到分布式能力实战(续篇)
flutter·开源·harmonyos
晚霞的不甘2 小时前
Flutter 与开源鸿蒙(OpenHarmony)生态融合:从 UI 渲染到系统级能力调用的全链路开发范式
flutter·开源·harmonyos
花先锋队长2 小时前
华为Mate X7:高级感,从何而来?
科技·华为·智能手机·harmonyos
2***65632 小时前
华为数据中心CE系列交换机级联M-LAG配置示例
服务器·华为·php
IT从业者张某某2 小时前
DAY2-Open Harmony PC 命令行适配指南(Windows版)-Tree命令行工具下载篇
harmonyos
嘴贱欠吻!2 小时前
开源鸿蒙-基于Flutter搭建GitCode口袋工具-2
flutter·华为·开源·harmonyos·gitcode
遇到困难睡大觉哈哈2 小时前
Harmony os——ArkTS 语言笔记(七):注解(Annotation)实战理解
java·笔记·ubuntu·harmonyos·鸿蒙