如何在 HarmonyOS 鸿蒙Next中监听屏幕的横竖屏状态,并使页面根据屏幕旋转自动适配?能不能给我一个代码案例,带效果那种?

发布于 1周前 作者 htzhanglong 来自 鸿蒙OS

如何在 HarmonyOS 鸿蒙Next中监听屏幕的横竖屏状态,并使页面根据屏幕旋转自动适配?能不能给我一个代码案例,带效果那种? 如何在 HarmonyOS 中监听屏幕的横竖屏状态,并使页面根据屏幕旋转自动适配?能不能给我一个代码案例,带效果那种?

#HarmonyOS最强问答官#

6 回复

设置横竖屏方法有两种:

  1. 配置module.json5中的orientation设置为auto_rotation
{
  "abilities": [
    {
      "orientation": "auto_rotation"
    }
  ]
}
  1. 代码层面setPreferredOrientation接口设置,同时开启监听display.on(“change”, callback);
import { window, display } from '@kit.ArkUI';

const TAG = 'foo'
const ORIENTATION: Array<string> = ['垂直', '水平', '反向垂直', '反向水平']

@Component
struct ScreenTest {
  @State rotation: number = 0
  @State message: string = ORIENTATION[this.rotation]

  aboutToAppear() {
    this.setOrientation()

    let callback = async (data: number) => {
      // ...
    }
    try {
      display.on("change", callback); // 监听屏幕状态改变
    } catch (exception) {
      console.error(TAG, 'Failed to register callback. Code: ' + JSON.stringify(exception));
    }
  }

  setOrientation() {
    try {
      window.getLastWindow(getContext(this), (err, data) => { // 获取window实例
        if (err.code) {
          console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(err));
          return;
        }
        let windowClass = data;
        console.info(TAG, 'Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));

        let orientation = window.Orientation.AUTO_ROTATION; // 设置窗口方向为传感器自动旋转模式。
        try {
          windowClass.setPreferredOrientation(orientation, (err) => {
            if (err.code) {
              console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(err));
              return;
            }
            console.info(TAG, 'Succeeded in setting window orientation.');
          });
        } catch (exception) {
          console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(exception));
        }
        ;
      });
    } catch (exception) {
      console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
    }
    ;
  }

  build() {
    Row() {
      Column() {
        Text(`${this.rotation}`).fontSize(25)
        Text(`${this.message}`).fontSize(25)
      }
      .width("100%")
    }
    .height("100%")
  }
}

更多关于如何在 HarmonyOS 鸿蒙Next中监听屏幕的横竖屏状态,并使页面根据屏幕旋转自动适配?能不能给我一个代码案例,带效果那种?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


怎么旋转都是0,

如果我想设置单个页面旋转,其它页面不旋转,怎么做,

旋转是统一的 不能指定某个页面,

在HarmonyOS鸿蒙Next中,监听屏幕的横竖屏状态并实现页面自动适配,可以使用Orientation组件和MediaQuery来实现。以下是一个简单的代码示例:

import { Orientation, MediaQuery, Flex, Text } from '@ohos/hmos';

@Entry
@Component
struct ScreenOrientationExample {
  @State isPortrait: boolean = true;

  aboutToAppear() {
    // 监听屏幕方向变化
    Orientation.onChange((orientation) => {
      this.isPortrait = orientation === Orientation.PORTRAIT;
    });
  }

  build() {
    // 根据屏幕方向调整布局
    Flex({ direction: this.isPortrait ? FlexDirection.Column : FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
      Text(this.isPortrait ? '竖屏模式' : '横屏模式')
        .fontSize(24)
        .fontColor(Color.White)
    }
    .width(MediaQuery.getWidth())
    .height(MediaQuery.getHeight())
    .backgroundColor(Color.Black)
  }
}

代码说明:

  1. Orientation.onChange:监听屏幕方向变化,orientation参数返回当前屏幕方向(Orientation.PORTRAITOrientation.LANDSCAPE)。
  2. MediaQuery.getWidth()MediaQuery.getHeight():获取屏幕的宽度和高度,确保布局适配屏幕尺寸。
  3. Flex组件:根据isPortrait状态调整布局方向,竖屏时为FlexDirection.Column,横屏时为FlexDirection.Row

效果:

当设备旋转时,页面会根据屏幕方向自动调整布局,并显示当前是竖屏还是横屏模式。

此代码在HarmonyOS鸿蒙Next中有效,可直接用于监听屏幕方向并实现页面适配。

在 HarmonyOS 鸿蒙Next 中,可以通过 OrientationEventListener 监听屏幕的横竖屏状态,并结合 DirectionalLayoutDependentLayout 实现自动适配。以下是一个简单的代码示例:

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;

public class MainAbility extends Ability {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbility");
    private DirectionalLayout layout;
    private Text textView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        layout = new DirectionalLayout(this);
        textView = new Text(this);
        textView.setText("当前屏幕状态:竖屏");
        layout.addComponent(textView);
        setUIContent(layout);

        CategoryOrientationAgent orientationAgent = new CategoryOrientationAgent(this);
        orientationAgent.register(new CategoryOrientationAgent.ICategoryOrientationDataCallback() {
            @Override
            public void onSensorDataModified(CategoryOrientationData data) {
                int orientation = data.getValues()[0];
                if (orientation == CategoryOrientation.ORIENTATION_0 || orientation == CategoryOrientation.ORIENTATION_180) {
                    textView.setText("当前屏幕状态:竖屏");
                } else {
                    textView.setText("当前屏幕状态:横屏");
                }
            }
        });
    }
}

效果:当屏幕旋转时,页面会自动更新显示当前屏幕状态为“竖屏”或“横屏”。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!