OpenHarmony开发者论坛

标题: 如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转? [打印本页]

作者: 北向实践与赋能    时间: 2024-1-4 11:33
标题: 如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?
[md]如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?
[/md]
作者: 北向实践与赋能    时间: 2024-1-4 11:34
标题: 如何监听当前屏幕的横竖屏状态?如何实现页面跟随屏幕横竖屏自动旋转?
[md]**关键字**
屏幕旋转,自动旋转

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

示例代码

```ts
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/do ... eferredorientation9

https://gitee.com/openharmony/do ... ayonaddremovechange
[/md]
作者: iamdaidai    时间: 2024-7-30 11:22
回复 北向实践与赋能: 请问下,您这个转了之后,按钮什么的能正常操作吗?我的转了,按钮等控件无法正常操作了




欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/) Powered by Discuz! X3.5