当前位置: 首页 > article >正文

OpenHarmony如何切换横竖屏?

前言

在日常开发中,大多APP可能根据实际情况直接将APP的界面方向固定,或竖屏或横屏。但在使用过程中,我们还是会遇到横竖屏切换的功能需求,可能是通过物理重力感应触发,也有可能是用户手动触发。所以本文主要带大家了解在OpenAtom OpenHarmony(以下简称“OpenHarmony”)应用开发的过程中,如何在Stage模型和FA模型下使用对应的接口去完成横竖屏的切换。

本文中OpenHarmony版本为3.2 Beta4,API版本为9。开发板为DAYU200。

FA模型

FA模型下,setDisplayOrientation和setDisplayOrientation是切换横竖屏的接口。

文档:

context.setDisplayOrientation

setDisplayOrientation(orientation:bundle.DisplayOrientation, callback: AsyncCallback): 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来切换横竖屏。

文档:

在Stage模型中,使用到的主要是Window(窗口)。在设置横竖屏切换的时候,需要先使用getLastWindow()、createWindow()、findWindow()中的任一方法获取到Window实例,再通过此实例调用对应的方法,本文使用的是getLastWindow。

Window.getLastWindow

getLastWindow(ctx: BaseContext): Promise

获取当前应用内最后显示的窗口,使用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

设置窗口的显示方向属性,使用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()),大家可以在此基础上利用生命周期的回调,在合适的地方完成对应的操作。

经常有很多小伙伴抱怨说:不知道学习鸿蒙开发哪些技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?

为了能够帮助到大家能够有规划的学习,这里特别整理了一套纯血版鸿蒙(HarmonyOS Next)全栈开发技术的学习路线,包含了鸿蒙开发必掌握的核心知识要点,内容有(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、WebGL、元服务、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、OpenHarmony驱动开发、系统定制移植等等)鸿蒙(HarmonyOS NEXT)技术知识点。

在这里插入图片描述

《鸿蒙 (Harmony OS)开发学习手册》(共计892页):https://gitcode.com/HarmonyOS_MN/733GH/overview

如何快速入门?

1.基本概念
2.构建第一个ArkTS应用
3.……

开发基础知识:

1.应用基础知识
2.配置文件
3.应用数据管理
4.应用安全管理
5.应用隐私保护
6.三方应用调用管控机制
7.资源分类与访问
8.学习ArkTS语言
9.……

在这里插入图片描述

基于ArkTS 开发

1.Ability开发
2.UI开发
3.公共事件与通知
4.窗口管理
5.媒体
6.安全
7.网络与链接
8.电话服务
9.数据管理
10.后台任务(Background Task)管理
11.设备管理
12.设备使用信息统计
13.DFX
14.国际化开发
15.折叠屏系列
16.……

在这里插入图片描述

鸿蒙开发面试真题(含参考答案):https://gitcode.com/HarmonyOS_MN/733GH/overview

在这里插入图片描述

OpenHarmony 开发环境搭建

图片

《OpenHarmony源码解析》:https://gitcode.com/HarmonyOS_MN/733GH/overview

  • 搭建开发环境
  • Windows 开发环境的搭建
  • Ubuntu 开发环境搭建
  • Linux 与 Windows 之间的文件共享
  • ……
  • 系统架构分析
  • 构建子系统
  • 启动流程
  • 子系统
  • 分布式任务调度子系统
  • 分布式通信子系统
  • 驱动子系统
  • ……

图片

OpenHarmony 设备开发学习手册:https://gitcode.com/HarmonyOS_MN/733GH/overview

图片
在这里插入图片描述


http://www.kler.cn/news/289047.html

相关文章:

  • 科研绘图系列:R语言富集火山图和通路图(volcano plot pathway)
  • 实现流程化办公,可专注于开源可视化报表设计器!
  • F12抓包01:启动、面板功能介绍、语言设置、前端样式调试
  • 【#第三期实战营闯关作业 ## MindSearch在 Hugging FaceSpace的部署】
  • 缓存解决方案。Redis 和 Amazon ElastiCache 比较
  • lit-llama代码解析
  • 【C++ 面试 - STL】每日 3 题(五)
  • 解读GaussianTalker:利用音频驱动的基于3D高斯点染技术的实时高保真讲话头像合成
  • Idea_服务器自动化部署_傻瓜式教程
  • MySQL中的分组统计
  • 云计算环境下的数据治理
  • 学习之git
  • 算法设计:实验二贪心算法
  • wget下载速度受到哪些因素影响?
  • MySQL:简述多版本并发控制MVCC
  • 无人机之电池篇
  • Python与R的完美协作:深入解析subprocess模块调用R脚本的参数传递机制
  • 安装WMware和Ubuntu并使用xShell连接
  • Map排序与转换的深入探索:Java与Kotlin的实现与应用
  • 宝兰德多款仓颉开源项目获GitCode官方G-Star毕业认证,释放开发效率新动能
  • 将军百战死,程序十年成
  • Spring Cloud Eureka与Kubernetes的集成:服务发现的混合方案
  • YOLO-World: Real-Time Open-Vocabulary Object Detection:实时开放词汇对象检测
  • QT教程-十七,QTextBrowser
  • dnsperf测试dns性能
  • 春秋云镜initial
  • c++----杨辉三角(补充)
  • 学懂C++(五十一): C++ 陷阱:详解多重继承与钻石继承引发的二义性问题
  • 上门家政系统源码开发详解
  • 界面控件Telerik UI for ASP.NET Core 2024 Q2亮点 - AI与UI的融合