0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

OpenHarmony如何切换横竖屏?

OpenAtom OpenHarmony 来源:未知 2023-01-18 02:25 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

开源项目 OpenHarmony是每个人的 OpenHarmony 9579cde2-9692-11ed-bfe3-dac502259ad0.png

徐建国(坚果)

江苏润开鸿数字科技有限公司 生态技术专家

前言

在日常开发中,大多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 设置当前能力的显示方向(callback形式)。 系统能力: SystemCapability.Ability.AbilityRuntime.Core 参数:95a190e8-9692-11ed-bfe3-dac502259ad0.png   示例:
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%')
  }
}
上面这样写太乱了,我们可以封装一下:
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 参数:95cba716-9692-11ed-bfe3-dac502259ad0.png   返回值:95d47fa8-9692-11ed-bfe3-dac502259ad0.png   错误码: 以下错误码的详细介绍请参见窗口错误码。95fa15f6-9692-11ed-bfe3-dac502259ad0.png
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 参数:9610352a-9692-11ed-bfe3-dac502259ad0.png   返回值:963309f6-9692-11ed-bfe3-dac502259ad0.png   错误码: 以下错误码的详细介绍请参见窗口错误码。96482ffc-9692-11ed-bfe3-dac502259ad0.png
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));
}
完整代码
importWindowfrom'@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如何切换横竖屏?

文章出处:【微信公众号:OpenAtom OpenHarmony】欢迎添加关注!文章转载请注明出处。


声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 鸿蒙
    +关注

    关注

    60

    文章

    2862

    浏览量

    45366
  • OpenHarmony
    +关注

    关注

    31

    文章

    3927

    浏览量

    20726

原文标题:OpenHarmony如何切换横竖屏?

文章出处:【微信号:gh_e4f28cfa3159,微信公众号:OpenAtom OpenHarmony】欢迎添加关注!文章转载请注明出处。

收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    OpenHarmony年度课题管理办法

    OpenHarmony年度课题管理办法V1.0 第一章 总则 第一条 宗旨 围绕终端操作系统所面临的技术挑战,OpenHarmony项目群技术指导委员会(TSC)联合产学研各界,以
    的头像 发表于 11-12 16:55 434次阅读

    基于RK3568开发板显示调试适配方法(1)-如何在Uboot界面切换显示

    显示作为电子产品不可或缺的一部分,此文档的目的在于帮助用户调试适配其它显示。本文档将以调试适配7寸MIPI为例。本文档章节安排:第一章:帮助用户如何在Uboot界面切换显示
    的头像 发表于 11-07 16:19 554次阅读
    基于RK3568开发板显示<b class='flag-5'>屏</b>调试适配方法(1)-如何在Uboot界面<b class='flag-5'>切换</b>显示<b class='flag-5'>屏</b>

    液晶 智能显示模块有多个画面时怎么切换到另一个画面?

    请问 液晶智能显示模块有多个画面时怎么切换到另一个画面?
    发表于 10-25 10:46

    两款搭载KaihongOS的开鸿开发板被评为“OpenHarmony 明星开发板”

    OpenHarmony
    深开鸿
    发布于 :2025年09月11日 10:10:02

    HarmonyOS折叠镜头切换应用实践

    在2025华为开发者大会的图片和相机分论坛上,美颜相机分享了如何通过折叠镜头适配,打造多端一致的拍摄体验。随着华为折叠产品的不断丰富,相机开发在折叠上也面临独特技术难题,镜头选错导致黑屏、角度
    的头像 发表于 08-27 16:35 884次阅读
    HarmonyOS折叠<b class='flag-5'>屏</b>镜头<b class='flag-5'>切换</b>应用实践

    2025 OpenHarmony TSC年中技术与生态研讨会圆满举办

    2025 OpenHarmony TSC 年中技术与生态研讨会 圆满举办 8月1日,2025 OpenHarmony TSC年中技术与生态研讨会于中国上海顺利召开。 本次会议由OpenHarmony
    的头像 发表于 08-07 12:24 1431次阅读
    2025 <b class='flag-5'>OpenHarmony</b> TSC年中技术与生态研讨会圆满举办

    OpenHarmony2025年度竞赛训练营重磅开启

      OpenHarmony2025年度竞赛训练营       活动介绍 OpenHarmony竞赛训练营 旨在引导高校学生进行OpenHarmony产学研用,培养更多应用型人才和产业需求有效链接
    的头像 发表于 07-16 11:51 721次阅读

    桃芯科技获得OpenHarmony生态产品兼容性证书

    近日,由INGCHIPS自主研发的模组/开发板DB870CC1A顺利通过OpenHarmony 5.0.2 Release版本兼容性测评,并获得OpenHarmony生态产品兼容性证书!
    的头像 发表于 06-25 14:30 874次阅读

    泰克示波器MSO58B光标横竖切换操作指南与实用技巧

    是提升测量效率与精度的关键操作之一。本文将详细介绍MSO58B示波器的光标横竖切换方法、应用场景及实用技巧,帮助用户高效掌握这一核心功能。   一、光标切换的基本操作步骤 泰克MSO58B的光标
    的头像 发表于 05-26 17:08 1248次阅读
    泰克示波器MSO58B光标<b class='flag-5'>横竖</b><b class='flag-5'>切换</b>操作指南与实用技巧

    请问下,openharmony支持哪一款龙芯的开发板?有没有开源的龙芯的openharmony源码?

    想买个2k0300的开发板学习龙芯和openharmony,愣是没有看到提供openharmony源码的,也没与看到开源的代码。gitee上,openharmony的龙芯sig仓库也是关闭的,有没有人知道现在是什么情况?
    发表于 04-26 13:06

    2024年OpenHarmony社区年度激励公示

    在过去一年里,OpenHarmony项目群技术指导委员会(TSC)向所有参与者致以最诚挚的感谢!大家的积极参与和鼎力支持推动了OpenHarmony社区的持续繁荣与高质量发展。OpenHarmony
    的头像 发表于 04-21 18:17 939次阅读

    OpenHarmony5.0系统怎么去除锁直接进入界面?教你2步搞定

    本文介绍在OpenHarmony5.0Release操作系统下,去除锁开机后直接进入界面的方法。触觉智能PurplePiOH鸿蒙开发板演示,搭载了瑞芯微RK3566四核处理器,1TOPS算力NPU
    的头像 发表于 03-12 18:51 980次阅读
    <b class='flag-5'>OpenHarmony</b>5.0系统怎么去除锁<b class='flag-5'>屏</b>直接进入界面?教你2步搞定

    【北京迅为】itop-3568 开发板openharmony鸿蒙烧写及测试-第2章OpenHarmony v3.2-Beta4版本测试

    【北京迅为】itop-3568 开发板openharmony鸿蒙烧写及测试-第2章OpenHarmony v3.2-Beta4版本测试
    的头像 发表于 03-05 10:53 887次阅读
    【北京迅为】itop-3568 开发板<b class='flag-5'>openharmony</b>鸿蒙烧写及测试-第2章<b class='flag-5'>OpenHarmony</b> v3.2-Beta4版本测试

    【北京迅为】itop-3568 开发板openharmony鸿蒙烧写及测试-第1章 体验OpenHarmony—烧写镜像

    【北京迅为】itop-3568 开发板openharmony鸿蒙烧写及测试-第1章 体验OpenHarmony—烧写镜像
    的头像 发表于 03-04 16:31 880次阅读
    【北京迅为】itop-3568 开发板<b class='flag-5'>openharmony</b>鸿蒙烧写及测试-第1章 体验<b class='flag-5'>OpenHarmony</b>—烧写镜像

    OpenHarmony程序分析框架论文入选ICSE 2025

      近日,ICSE 2025软件工程实践Track放榜,面向OpenAtom OpenHarmony(以下简称“OpenHarmony”)的ArkTS程序分析基础框架--方舟程序分析器(论文题目为
    的头像 发表于 01-02 13:41 1862次阅读
    <b class='flag-5'>OpenHarmony</b>程序分析框架论文入选ICSE 2025