HarmonyOS NEXT实战:获取窗口属性

5 阅读2分钟

##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##

参考资料: developer.huawei.com/consumer/cn…

在Stage模型下,管理应用窗口的典型场景有:

  • 设置应用主窗口属性及目标页面
  • 设置应用子窗口属性及目标页面
  • 体验窗口沉浸式能力
  • 设置悬浮窗
  • 监听窗口不可交互与可交互事件

以下介绍获取窗口属性的方式: 第1步:获取Window类

getLastWindow(ctx: BaseContext): Promise<Window>

获取当前应用内最上层的子窗口,若无应用子窗口,则返回应用主窗口,使用Promise异步回调。

第2步:获取当前窗口的属性

getWindowProperties(): WindowProperties

获取当前窗口的属性,返回WindowProperties。

WindowProperties各属性解释

  • windowRect:窗口尺寸,可在页面生命周期onPageShow或应用生命周期onForeground阶段获取。
  • drawableRect:窗口内的可绘制区域尺寸,其中左边界上边界是相对于窗口计算。在Stage模型下,需要在调用loadContent()或setUIContent()加载页面内容后使用该接口。
  • type:窗口类型。
  • isFullScreen:是否全屏,默认为false。true表示全屏;false表示非全屏。
  • isLayoutFullScreen:窗口是否为沉浸式且处于全屏模式(不在悬浮窗、分屏等场景下),默认为false。true表示沉浸式且处于全屏模式;false表示非沉浸式或非全屏模式。
  • focusable:窗口是否可聚焦,默认为true。true表示可聚焦;false表示不可聚焦。
  • touchable:窗口是否可触摸,默认为true。true表示可触摸;false表示不可触摸。
  • brightness:屏幕亮度。该参数为浮点数,可设置的亮度范围为[0.0, 1.0],其取1.0时表示最大亮度值。如果窗口没有设置亮度值,表示亮度跟随系统,此时获取到的亮度值为-1。
  • isKeepScreenOn:屏幕是否常亮,默认为false。true表示常亮;false表示不常亮。
  • isPrivacyMode:隐私模式,默认为false。true表示模式开启;false表示模式关闭。
  • isTransparent:窗口背景是否透明。默认为false。true表示透明;false表示不透明。
  • id:窗口ID,默认值为0,该参数应为整数。
  • displayId:窗口所在屏幕ID,默认返回主屏幕ID,该参数应为整数。

以下以获取窗口属性的宽高为例,实战代码如下:

import { common } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct GetWindowPropertiesPage {
  @State windowWidth: number = 0
  @State windowHeight: number = 0

  aboutToAppear(): void {
    try {
      let context = getContext(this) as common.UIAbilityContext;
      let promise = window.getLastWindow(context);
      promise.then((data) => {
        //获取窗口对象
        let windowClass = data;
        try {
          //获取窗口属性
          let properties = windowClass.getWindowProperties();
          let rect = properties.windowRect;
          //rect.width: 窗口宽度;rect.height: 窗口高度
          this.windowWidth = px2vp(rect.width)
          this.windowHeight = px2vp(rect.height)
        } catch (exception) {
          console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception));
        }
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
      }).catch((err: BusinessError) => {
        console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
      });
    } catch (exception) {
      console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
    }
  }

  build() {
    Column({ space: 10 }) {
      Text('GetWindowProperties Page')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)

      Text(`windowWidth = ${this.windowWidth}`)
      Text(`windowHeight = ${this.windowHeight}`)
    }
    .height('100%')
    .width('100%')
  }
}