#鸿蒙通关秘籍#如何在鸿蒙应用内实现全局悬浮窗

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
CyberCobra

在鸿蒙应用内实现全局悬浮窗,需要通过创建子窗口并设置相关手势监听来实现。以下是详细步骤:

  1. 初始化和创建子窗口

    FloatManager.init(windowStage);
    init(windowStage: window.WindowStage) {
        this.windowStage_ = windowStage
    }
    
    showSubWindow() {
        if (this.windowStage_ != null) {
            this.windowStage_.createSubWindow("HarmonyWorld", (err: BusinessError, data) => {
                this.sub_windowClass = data;
                this.sub_windowClass.moveWindowTo(this.locationX, this.locationY, (err: BusinessError) => { ... });
                this.sub_windowClass.resize(this.size, this.size, (err: BusinessError) => { ... });
                this.sub_windowClass.setUIContent("pages/float/FloatPage", (err: BusinessError) => {
                    (this.sub_windowClass as window.Window).showWindow((err: BusinessError) => {
                        data.setWindowBackgroundColor("#00000000");
                    });
                });
            });
        } else {
            Log.error(TAG, 'Failed to create the subwindow. Cause: windowStage_ is null');
        }
    }
    
  2. 手势监听设置

    @Entry
    @Component
    export struct FloatPage {
        private context = getContext(this) as common.UIAbilityContext
        build() {
            Column() {
                Image($r('app.media.mobile_dev'))
                  .width('100%')
                  .height('100%')
            }
            .gesture(
                GestureGroup(GestureMode.Exclusive,
                    PanGesture()
                      .onActionUpdate((event: GestureEvent | undefined) => {
                          if (event) {
                              FloatManager.updateLocation(event.offsetX, event.offsetY)
                          }
                      }),
                    TapGesture({ count: 1 })
                      .onAction(() => {
                          router.pushUrl(...)
                      }))
            )
        }
    }
    
  3. 地址更新

    updateLocation(offSetX: number, offsetY: number) {
        if (this.sub_windowClass != null) {
            this.locationX = this.locationX + offSetX;
            this.locationY = this.locationY + offsetY;
            this.sub_windowClass.moveWindowTo(this.locationX, this.locationY, (err: BusinessError) => { ... });
        }
    }
    
分享
微博
QQ
微信
回复
2天前
相关问题
基于子窗口实现应用悬浮
695浏览 • 1回复 待解决