如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?

北向实践与赋能 显示全部楼层 发表于 2024-1-4 11:33:58

如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

精彩评论2

北向实践与赋能

沙发 发表于 2024-1-4 11:34:39

如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?

关键字 屏幕旋转,自动旋转

解决方案 如何监听当前屏幕的横竖屏状态? 应用可以通过diplay.on监听屏幕状态改变   如何实现页面跟随屏幕横竖屏自动旋转? 1、Abilty级别配置:在模块配置文件module.json5中将EntryAbility设置为"orientation"; 2、动态设置:使用window.setPreferredOrientation设置窗口方向

示例代码

import window from '@ohos.window';
import display from '@ohos.display';

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

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

  aboutToAppear() {
    this.setOrientation()

    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() {
    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%")
  }
}

参考资料

https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-window.md#setpreferredorientation9

https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-display.md#displayonaddremovechange

iamdaidai

发表于 2024-7-30 11:22  IP属地: 广东省广州市

回复 北向实践与赋能: 请问下,您这个转了之后,按钮什么的能正常操作吗?我的转了,按钮等控件无法正常操作了

【1 条回复】

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部