如何实现page页面的横竖屏切换

如何实现page页面的横竖屏切换

HarmonyOS
2024-07-22 12:30:20
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
jshyb

使用setPreferredOrientation设置横竖屏切换:setPreferredOrientation

import { window } from '@kit.ArkUI'; 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
  private portrait: boolean = true 
  changeOrientation = () => { 
    // 获取当前页面 
    let context = getContext(this) 
    window.getLastWindow(context).then((mainWindow) => { 
      this.changeOrientationInternal(mainWindow) 
    }).catch((error: ESObject) => { 
      console.log('getMainWindow error: ' + JSON.stringify(error)) 
    }) 
  } 
 
  changeOrientationInternal(lastWindow: window.Window) { 
    if (this.portrait) { 
      // 切换成横屏 
      lastWindow.setPreferredOrientation(window.Orientation.LANDSCAPE).then(() => { 
        console.log('setPreferredOrientation success') 
        this.portrait = !this.portrait 
      }).catch((error: ESObject) => { 
        console.log('setPreferredOrientation failure' + JSON.stringify(error)) 
      }) 
    } else { 
      // 切换成竖屏 
      lastWindow.setPreferredOrientation(window.Orientation.PORTRAIT).then(() => { 
        console.log('setPreferredOrientation success') 
        this.portrait = !this.portrait 
      }).catch((error: ESObject) => { 
        console.log('setPreferredOrientation failure: ' + JSON.stringify(error)) 
      }) 
    } 
  } 
 
  build() { 
    Column() { 
      Text(this.message) 
        .id('Index19HelloWorld') 
        .fontSize(50) 
        .fontWeight(FontWeight.Bold) 
        .alignRules({ 
          center: { anchor: '__container__', align: VerticalAlign.Center }, 
          middle: { anchor: '__container__', align: HorizontalAlign.Center } 
        }) 
      Button('横竖屏切换') 
        .onClick(() => { 
          this.changeOrientation() 
        }) 
    } 
    .height('100%') 
    .width('100%') 
    .backgroundColor(Color.Green) 
  }}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
分享
微博
QQ
微信
回复
2024-07-22 20:13:20
相关问题
页面横竖如何进行切换
1224浏览 • 1回复 待解决
如何进行页面横竖切换
2880浏览 • 1回复 待解决
HarmonyOS 横竖切换实现过于繁琐
979浏览 • 1回复 待解决
HarmonyOS 小窗下如何实现横竖切换
955浏览 • 1回复 待解决
HarmonyOS 横竖切换
1113浏览 • 1回复 待解决
HarmonyOS 横竖切换问题
1137浏览 • 1回复 待解决
HarmonyOS 监听横竖切换
948浏览 • 1回复 待解决
求大佬告知如何切换横竖
3050浏览 • 1回复 待解决
如何监听设备横竖切换状态呢
2564浏览 • 1回复 待解决
HarmonyOS 平板无法正确横竖切换
899浏览 • 1回复 待解决
如何监听手机屏幕的横竖切换
1212浏览 • 1回复 待解决
鸿蒙JS 框架中如何主动切换横竖?
5694浏览 • 1回复 待解决
HarmonyOS page页面的问题
781浏览 • 1回复 待解决
鸿蒙横竖切换监听,需要这个功能
12183浏览 • 3回复 已解决
如何横竖切换更自然一些
1333浏览 • 1回复 待解决