HarmonyOS 如何获取屏幕宽高并设置为全局供所有页面调用?

如题:HarmonyOS 如何获取屏幕宽高并设置为全局供所有页面调用?

阅读 605
1 个回答

可以在EntryAbility中的onWindowStageCreate中用display来获取屏幕的宽高,并将其通过AppStorage进行存储,然后在需要使用的页面处使用,以下是简单示例:

// EntryAbility.ets 
import display from '@ohos.display'; // 屏幕属性 
let screenHeight: number = 0;  // 保存屏幕高度(px) 
let screenWidth: number = 0;  // 保存屏幕宽度(px) 
export default class EntryAbility extends UIAbility { 
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 
  } 
  onWindowStageCreate(windowStage: window.WindowStage): void { 
    // 通过屏幕属性获取屏幕宽高 
    display.getAllDisplays((err,data) => { 
      screenHeight = data[0].height; 
      screenWidth = data[0].width; 
      // 使用AppStorage存储获取的屏幕宽高 
      AppStorage.setOrCreate('globalScreenHeight', screenHeight); 
      AppStorage.setOrCreate('globalScreenWidth', screenWidth); 
      hilog.info(0x0000, 'testTag', `${screenHeight} --- ${screenWidth}`, 'Ability onWindowStageCreate') 
    }) 
  } 
  onForeground(): void { 
    // Ability has brought to foreground 
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 
  } 
  onBackground(): void { 
    // Ability has back to background 
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 
  } 
}   
// Index.ets 
// 在页面中使用 
@Entry 
@Component 
struct Index { 
  @State screenHeight: number | undefined = AppStorage.get('globalScreenHeight'); 
  build() { 
    Column() { 
      Text('屏幕高度:' + this.screenHeight) 
    } 
  } 
}

屏幕属性请参考: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-display-V5

AppStorage请参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-appstorage-V5

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进