HarmonyOS 鸿蒙Next如何监测屏幕的横竖屏切换?
HarmonyOS 鸿蒙Next如何监测屏幕的横竖屏切换?
import window from '@ohos.window';
import display from ‘@ohos.display’;
const TAG = ‘foo’
const ORIENTATION: Array<string> = [‘垂直’,‘平’, ‘反向垂直’, ‘反向水平’]
struct OrientationPage {
  @State rotation: number = 0
  @State message: string = ORIENTATION[this.rotation]
  @Watch(‘setWindowLayOut’)
  @State isLandscape: boolean = false;// 是否横屏状态
  aboutToAppear() {
    this.setOrientation(1)
    let callback = async () => {
      let d = await display.getDefaultDisplaySync()
      this.rotation = d.rotation
      this.message = ORIENTATION[this.rotation]
      console.info(TAG, JSON.stringify(d))
    }
    try {
      display.on(“change”, callback);//监听屏幕状态改变
    } catch (exception) {
      console.error(TAG, 'Failed to register callback. Code: ’ + JSON.stringify(exception));
    }
  }
  setOrientation(type : number) {
    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 : number;
      if (type === 1) {
        orientation = window.Orientation.AUTO_ROTATION; //设置窗口方向为传感器自动旋转模式。
      } else {
        orientation = window.Orientation.UNSPECIFIED; //设置窗口方向为传感器锁定。
      }
      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));
    } ;
  }
  setWindowLayOut() {
    // 调用该接口手动改变设备横竖屏状态(设置全屏模式,先强制横屏,再加上传感器模式)
    window.getLastWindow(getContext(this)).then((windowClass) => {
      if (this.isLandscape) {
        console.log(‘设置屏幕横屏’)
        windowClass.setPreferredOrientation(window.Orientation.AUTO_ROTATION_LANDSCAPE);
      } else {
        console.log(‘设置屏幕竖屏’)
        windowClass.setPreferredOrientation(window.Orientation.AUTO_ROTATION_PORTRAIT);
      }
    });
  }
  build() {
    Row() {
      Column() {
        Text(${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.rotation})
          .fontSize(25)
        Text(${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.message})
          .fontSize(25)
        Button(‘全屏’)
          .width(140)
          .onClick(() => {
            this.isLandscape = !this.isLandscape; // 设置横屏
          });
      }
      .width(“100%”)
    }
    .height(‘100%’)
  }
}
更多关于HarmonyOS 鸿蒙Next如何监测屏幕的横竖屏切换?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
HarmonyOS 鸿蒙Next监测屏幕的横竖屏切换,可以通过监听屏幕状态改变事件来实现。以下是具体方法:
首先,需要在应用的模块配置文件module.json5中配置相关设置,确保应用具备横竖屏切换能力。如果希望横竖屏切换受系统控制(打开自动旋转生效,关闭失效),可以将"orientation"属性设置为"auto_rotation_restricted"。
其次,在应用代码中,可以使用ArkUI框架提供的display模块来监听屏幕状态改变。通过调用display.on(“change”, callback)方法,可以注册一个回调函数,当屏幕状态发生改变(如横竖屏切换)时,该函数将被触发。
在回调函数中,可以获取当前的屏幕方向,并根据需要执行相应的操作,如调整页面布局、更新UI元素等。
示例代码如下:
import { display, window } from '@kit.ArkUI';
// 监听屏幕状态改变
display.on("change", () => {
    // 获取当前窗口并设置方向(可选)
    window.getLastWindow().then((windowClass) => {
        // 此处可以添加逻辑来处理屏幕方向改变
    });
});
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。
        
      
                  
                  
                  
