前言

在日常开发中,大多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如何切换横竖屏?的更多相关文章

  1. Android 切换横竖屏

    一个项目一般会自己先定义项目是横屏还是竖屏但是也有可以横屏和竖屏之间切换的activty. 切换横竖屏的方法: //判断当前屏幕方向if(getRequestedOrientation() == Ac ...

  2. 避免切换横竖屏Fragment的重复加载导致UI混乱

    当我们切换横竖屏时 Activity的生命周期就会重走一遍,自然 其中的Fragment的生命周期也就重新走了一遍,实践证明 当熄屏 再开屏时 Fragment的生命周期也会重走一遍 解决方案: an ...

  3. ListView 在设备切换横竖屏时保存状态

    比如listview在设备切换横竖屏时,仍然需要保证position, activity - > onSaveInstanceState  - > restoreInstanceState ...

  4. Android切换横竖屏不销毁前台Activity,也不影响后台Activity

    在切换屏幕方向的时候,Activity默认会走销毁->重建的生命周期,而有时候我们不希望如此,就需要做些额外的设置了: 1.在AndroidMainifest.xml中对应的Activity标签 ...

  5. 切换横竖屏的时候Activity的生命周期变化情况

    关于这个,有个博客说得比较清楚:http://blog.csdn.net/wulianghuan/article/details/8603982,直接给出链接,哈哈哈.

  6. Android应用:横竖屏切换总结

    眨眼间,已经到了2016你年春节前,离上一篇博客的时间已经有6个月多,回想起这半年的种种,不得不说,学习和工作实在是太忙了,或许这就是程序员的真实写照吧. 写博客之初,主要的目的还是为了把自己的学习痕 ...

  7. Android横竖屏切换及其对应布局加载问题

    第一,横竖屏切换连带横竖屏布局问题: 如果要让软件在横竖屏之间切换,由于横竖屏的高宽会发生转换,有可能会要求不同的布局. 可以通过以下两种方法来切换布局: 1)在res目录下建立layout-land ...

  8. Android横竖屏切换重载问题与小结

    (转自:http://www.cnblogs.com/franksunny/p/3714442.html) (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com ...

  9. Android 横竖屏切换小结

    (自己体会:每次横竖屏自动切时都会run Activity的onCreate,即相当后重新进入Activity初始化一样:) 转自:http://www.cnblogs.com/franksunny/ ...

  10. Android横竖屏切换小结

    Android横竖屏切换小结 (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com/franksunny/635350788930000000.pdf) And ...

随机推荐

  1. re.sub参数之回调函数

    from calendar import month_abbr import re def change_date(m): mon_name = month_abbr[int(m.group(1))] ...

  2. 第一百一十六篇: JavaScript理解对象

    好家伙,本篇为<JS高级程序设计>第八章"对象.类与面向对象编程"学习笔记   1.关于对象 ECMA-262将对象定义为一组属性的无序集合.严格来说,这意味着对象就是 ...

  3. python代码,读取一个txt文件,将其中的每一行开头加上一个字母a,每一行的结尾加上一个字母b

    with open('name.txt', 'r+') as file: lines = file.readlines() file.seek(0) # 将文件指针移回文件开头 file.trunca ...

  4. vivo 在离线混部探索与实践

    作者:来自 vivo 互联网服务器团队 本文根据甘青.黄荣杰老师在"2023 vivo开发者大会"现场演讲内容整理而成. 伴随 vivo 互联网业务的高速发展,数据中心的规模不断扩 ...

  5. 使用 maven 的 `wagon-maven-plugin`插件 快速部署 到不同的 环境

    profile 在pom文件中配置 开发和测试环境的 profile信息, <profiles> <profile> <!-- 开发环境 --> <id> ...

  6. Java -----多线程 创建线程的方式三: 实现Callable接口----JDK 5.0 新增

    1 package bytezero.thread2; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent. ...

  7. 按值传递,引用传递 浅析java String ,对象与对象引用的区别

    目录 一.前言 二.何谓对象? 三.何谓对象引用? 四.创建对象 Vehicle veh1 = new Vehicle(); 五.参数传值 六.Java Sting 最后!有错误的地方欢迎指正 一.前 ...

  8. Codeforces(1500板刷)

    目录 写在前面 1. A. Did We Get Everything Covered?(构造.思维) 题目链接 题意 题解 代码 总结 2 F. Greetings(离散化+树状数组) 题目链接 题 ...

  9. CPNtools协议建模安全分析--ML语言之颜色集定义(六)

    之前一直在怀疑我是不是因为对CPN Tools的原理结构还是不够理解,对Petri网的还没有弄清楚,越往后面看这种质疑越来越严重. 之前说CPN Tools在对称和非对称算法中不能形式化的问题,后续看 ...

  10. 基于 XAF Blazor 的规则引擎编辑器

    开源项目地址:https://gitee.com/lowcodexaf/rules-engine-editor 前言 本项目是基于XAFBlazor的规则引擎编辑器,规则引擎采用的是微软开源的Rule ...