HarmonyOS鸿蒙Next中工程代码如何开启平板设备横竖屏自动切换?

HarmonyOS鸿蒙Next中工程代码如何开启平板设备横竖屏自动切换? 创建了项目功能,运行,模拟器默认运行效果为手机竖屏,平板横屏,系统关闭了锁定方向时候,不能跟随设备做出横竖屏切换,请问是否要配置哪里或者需要做怎样的开发适配(有文档吗)?
另外需求为:手机端固定为竖屏(不管系统是否锁定方向),平板端自适应系统的横竖屏切换(如过系统锁定方向则也跟着锁定)

3 回复

在onWindowStageCreate可以使用this.context,如果使用getContext(this),获取不到context:

let preferences: dataPreferences.Preferences | null = null;
class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => {
            if (err) {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                return;
            }
            preferences = val;
            console.info("Succeeded in getting preferences.");
        })
    }
}

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5

更多关于HarmonyOS鸿蒙Next中工程代码如何开启平板设备横竖屏自动切换?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,要实现平板设备的横竖屏自动切换,可以通过配置config.json文件中的abilities属性来设置。具体步骤如下:

  1. 打开工程中的config.json文件。
  2. 找到abilities节点,该节点描述了应用的能力配置。
  3. abilities节点下,找到需要支持横竖屏切换的ability
  4. 在该ability中添加orientation属性,并将其值设置为unspecified,以支持自动横竖屏切换。

示例配置如下:

{
  "module": {
    "abilities": [
      {
        "name": ".MainAbility",
        "orientation": "unspecified"
      }
    ]
  }
}

通过以上配置,应用在平板设备上运行时,系统将根据设备当前的物理方向自动调整应用的显示方向,实现横竖屏自动切换。

在HarmonyOS鸿蒙Next中,开启平板设备横竖屏自动切换需在工程代码中设置 configChanges 属性。具体步骤:

  1. 打开 AndroidManifest.xml 文件。
  2. 在对应的 <activity> 标签中添加 android:configChanges="orientation|keyboardHidden|screenSize"
  3. onConfigurationChanged 方法中处理屏幕方向变化时的逻辑。

此外,确保在 MainAbilityonConfigurationUpdated 方法中监听配置变化,并调整UI布局。

这些步骤确保应用在不同屏幕方向下自动调整布局,提供良好的用户体验。

回到顶部