【HarmonyOS应用开发】鸿蒙应用实现横竖屏切换的两种方式以及注意事项

【HarmonyOS应用开发】鸿蒙应用实现横竖屏切换的两种方式以及注意事项

一、概述

目前共还有两种方式实现应用的横竖屏切换。 1、静态配置 2、动态调用接口

注意事项: 1、设置主窗口的显示方向属性。仅在支持跟随sensor旋转的设备上生效,子窗口调用后不生效。 2、module.json5中。"orientation": "auto_rotation"随传感器旋转 需要在系统下滑菜单中,放开自动锁定状态才可生效。 3、退出逻辑的闭环。例如只有进入当前页面需要某种横竖屏状态,推出该界面时,需要将状态重置回原先。

二、步骤解释和源码DEMO

1、静态配置: 在module.json5添加属性"orientation" 具体的值。数值详情参见:developer.huawei.com/consumer/cn...

常用配置值: 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) // 去注册回调

引用资料地址:

官方文档,横竖屏切换内容: developer.huawei.com/consumer/cn...

横竖屏切换配置,数值的具体参数值介绍:developer.huawei.com/consumer/cn...

developer.huawei.com/consumer/cn...

相关推荐
万少6 小时前
告别素材焦虑!用 AI 一键生成鸿蒙项目图片素材
ai编程·harmonyos
wszy18097 小时前
外部链接跳转:从 App 打开浏览器的正确姿势
java·javascript·react native·react.js·harmonyos
奋斗的小青年!!9 小时前
OpenHarmony Flutter 拖拽排序组件性能优化与跨平台适配指南
flutter·harmonyos·鸿蒙
sinat_384241099 小时前
HarmonyOS应用开发的trae cn全面实战指南
华为·harmonyos
小雨下雨的雨10 小时前
Flutter 框架跨平台鸿蒙开发 —— Stack 控件之三维层叠艺术
flutter·华为·harmonyos
行者9611 小时前
OpenHarmony平台Flutter手风琴菜单组件的跨平台适配实践
flutter·harmonyos·鸿蒙
Van_Moonlight12 小时前
RN for OpenHarmony 实战 TodoList 项目:已完成未完成数量显示
javascript·开源·harmonyos
陈_杨12 小时前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP--ArkTS 卡片开发完全指南
前端·harmonyos
陈_杨12 小时前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP--ArkTS 卡片刷新机制
前端·harmonyos