HarmonyOS鸿蒙Next中如何检测当前屏幕的方向变化(横屏或竖屏)?如何让页面自动适应屏幕的横竖屏切换并进行旋转?

HarmonyOS鸿蒙Next中如何检测当前屏幕的方向变化(横屏或竖屏)?如何让页面自动适应屏幕的横竖屏切换并进行旋转?

  • 如何检测当前屏幕的方向变化(横屏或竖屏)?
  • 如何让页面自动适应屏幕的横竖屏切换并进行旋转?
3 回复
  1. 可以通过display.on可以监听屏幕状态改变。其中可以在module.json5中设置EntryAbilityorientation,或者使用window.setPreferredOrientation动态设置窗口横竖屏。

  2. 当监听到变化时,可以通过发布订阅的方式全局通知。module.json5里面配置 "orientation": "auto_rotation",让屏幕自动旋转。

    win.setPreferredOrientation(window.Orientation.PORTRAIT),设置横屏或者竖屏。

    win.on("windowSizeChange", (data) => {}),监听横竖屏变化。

    onConfigurationUpdate生命周期中监听屏幕变化。

对于窗口的横竖屏可以借助display.getDefaultDisplaySync().orientation这个属性来判断屏幕目前所处的横竖屏状态。具体参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-display-V5#orientation10

具体实践参考:https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-landscape-and-portrait-development-V5

更多关于HarmonyOS鸿蒙Next中如何检测当前屏幕的方向变化(横屏或竖屏)?如何让页面自动适应屏幕的横竖屏切换并进行旋转?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,检测当前屏幕方向变化并让页面自动适应横竖屏切换,可以通过Orientation组件和Configuration类来实现。

  1. 检测屏幕方向变化:
  • 使用Configuration类可以获取当前屏幕的方向信息。通过监听Configuration的变化,可以实时检测屏幕方向的改变。
  • 示例代码:
import Configuration from '@ohos.app.ability.Configuration';

// 获取当前Configuration
let config = Configuration.getGlobalConfiguration();

// 监听Configuration变化
config.on('change', (newConfig) => {
    if (newConfig.orientation === Configuration.Orientation.ORIENTATION_LANDSCAPE) {
        console.log('当前为横屏');
    } else if (newConfig.orientation === Configuration.Orientation.ORIENTATION_PORTRAIT) {
        console.log('当前为竖屏');
    }
});
  1. 页面自动适应屏幕方向:
  • 使用Orientation组件可以实现页面的自动旋转。通过设置Orientation的方向属性,页面可以根据屏幕方向自动调整布局。
  • 示例代码:
import Orientation from '@ohos.orientation';

// 设置页面方向为自动
Orientation.setOrientation(Orientation.OrientationType.AUTO);

// 监听方向变化
Orientation.on('orientationChange', (orientation) => {
    if (orientation === Orientation.OrientationType.LANDSCAPE) {
        console.log('页面调整为横屏');
    } else if (orientation === Orientation.OrientationType.PORTRAIT) {
        console.log('页面调整为竖屏');
    }
});

通过上述方法,可以实现HarmonyOS鸿蒙Next中屏幕方向变化的检测和页面的自动适应旋转。

在HarmonyOS鸿蒙Next中,可以通过监听Configuration的变化来检测屏幕方向。使用AbilityContextonConfigurationUpdate方法,监听Configuration中的orientation属性变化。若orientationOrientation.VERTICAL则为竖屏,Orientation.HORIZONTAL则为横屏。

要让页面自动适应屏幕切换,可在config.json中为指定的AbilityPage设置orientationunspecifiedsensor,系统会根据设备方向自动调整页面布局。

回到顶部