HarmonyOS 如何在竖向锁定的ability旋转页面

如何在竖向锁定的ability让某个页面进行横向显示,将页面进行竖向布局。希望通过旋转的方式让它横向显示但使用rotate进行旋转时,页面进行旋转宽高交换,导致布局会出现错乱。当获取屏幕宽高之后,进行动态反向设置布局宽高,也没有效果。

HarmonyOS
2024-12-24 16:41:29
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

示例参考如下:

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

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

@Entry
@Component
struct Index {
  @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实例
      window.getLastWindow(getContext(this), (err, data) => {
        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() {
        TextInput()
          .backgroundColor(Color.Pink)
          .width('100%')
        Text(`${this.rotation}`).fontSize(25)
        Text(`${this.message}`).fontSize(25)
      }
      .width("100%")
    }
    .height("100%")
  }
}
分享
微博
QQ
微信
回复
2024-12-24 19:29:50
相关问题
如何实现文本内容竖向布局
693浏览 • 1回复 待解决
如何实现文本竖向排列
2657浏览 • 1回复 待解决
证书锁定功能示例有哪些?
937浏览 • 1回复 待解决
HarmonyOS Image配置图片如何旋转
129浏览 • 1回复 待解决
HarmonyOS ability 如何返回上一个 ability
414浏览 • 1回复 待解决
HarmonyOS 如何实现旋转地球效果?
112浏览 • 1回复 待解决