【问题现象】
如何实现独立子窗口的能力?即创建一个在主窗口退后台时仍可独立在前台显示的子窗口。
【背景知识】
独立子窗口是HarmonyOS 7.0交付的新需求,在官网文档中称作独立窗口。独立子窗口属于辅助窗口的一种,可以在主窗口退后台时独立在前台显示。更多关于窗口类型的介绍可参考窗口类型概述。
【解决方案】
使用createSubWindowWithOptions接口创建子窗口时,配置zLevelAboveParentLoosened属性为true,即可实现独立子窗口的效果。该配置使子窗口在主窗口退后台时仍可独立在前台显示。需要设备支持HarmonyOS 7.0 Beta1及以上版本。
在UIAbility的onWindowStageCreate生命周期回调中获取并存储WindowStage实例,代码示例如下:
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
// 存储windowStage实例供后续使用
AppStorage.setOrCreate('windowStage', windowStage);
}
}创建独立子窗口主页面代码示例如下:
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
build() {
Column() {
Button('创建独立子窗口')
.onClick(async () => {
try {
// 获取存储的windowStage实例
const windowStage = AppStorage.get<window.WindowStage>('windowStage');
if (!windowStage) {
console.error('获取windowStage失败');
return;
}
// 创建独立子窗口的配置选项
let subWindowOptions: window.SubWindowOptions = {
title: 'SubWindow',
decorEnabled: true,
zLevelAboveParentLoosened: true // 关键参数:使子窗口成为独立子窗口
};
const subWin = await windowStage.createSubWindowWithOptions('SubWindowName', subWindowOptions);
await subWin.setUIContent('pages/SubWindow')
await subWin.resize(1200,800)
await subWin.moveWindowTo(500,500)
await subWin.setWindowFocusable(true)
await subWin.showWindow()
} catch (err) {
let error = err as BusinessError;
console.error(`创建独立子窗口失败: ${JSON.stringify(error)}`);
}
})
}
}
}独立子窗口加载SubWindow.ets代码示例如下:
@Entry
@Component
struct SubWindow {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('PageHelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}调用时机:在主窗口创建完成后,通过存储的windowStage实例调用createSubWindowWithOptions接口创建子窗口时传入配置项。SubWindowOptions需配置title参数指定窗口标题,decorEnabled参数设置为true启用窗口装饰,关键参数为zLevelAboveParentLoosened,设置为true即可使该子窗口成为独立子窗口。创建成功后,可依次调用setUIContent加载子窗口页面、resize设置窗口大小、moveWindowTo设置窗口位置、setWindowFocusable设置窗口可聚焦、showWindow显示窗口。









































苏公安网备 32011402010933号