鸿蒙OS元服务开发:【(Stage模型)设置应用主窗口】

发布于:2024-04-03 ⋅ 阅读:(173) ⋅ 点赞:(0)

一、设置应用主窗口说明

在Stage模型下,应用主窗口由UIAbility创建并维护生命周期。在UIAbility的onWindowStageCreate回调中,通过WindowStage获取应用主窗口,即可对其进行属性设置等操作。还可以在应用配置文件中设置应用主窗口的属性,如最大窗口宽度maxWindowWidth等。

二、开发步骤

1.获取应用主窗口。

通过getMainWindow接口获取应用主窗口。

2.设置主窗口属性。

可设置主窗口的背景色、亮度值、是否可触等多个属性,开发者可根据需要选择对应的接口。本示例以设置“是否可触”属性为例。

3.为主窗口加载对应的目标页面。

通过loadContent接口加载主窗口的目标页面。

搜狗高速浏览器截图20240326151450.png

鸿蒙OS开发 更多内容↓点击 HarmonyOS与OpenHarmony技术
鸿蒙技术文档 开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。

import UIAbility from '@ohos.app.ability.UIAbility';

export default class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage) {
        // 1.获取应用主窗口。
        let windowClass = null;
        windowStage.getMainWindow((err, data) => {
            if (err.code) {
                console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
                return;
            }
            windowClass = data;
            console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
            // 2.设置主窗口属性。以设置"是否可触"属性为例。
            let isTouchable = true;
            windowClass.setWindowTouchable(isTouchable, (err) => {
                if (err.code) {
                    console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err));
                    return;
                }
                console.info('Succeeded in setting the window to be touchable.');
            })
        })
        // 3.为主窗口加载对应的目标页面。
        windowStage.loadContent("pages/page2", (err) => {
            if (err.code) {
                console.error('Failed to load the content. Cause:' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in loading the content.');
        });
    }
};