HarmonyOS 鸿蒙Next弹窗的controller抽取到静态类的静态方法中控制展示弹窗无法展示

HarmonyOS 鸿蒙Next弹窗的controller抽取到静态类的静态方法中控制展示弹窗无法展示 主页的弹窗太多了,希望抽取弹窗的展示逻辑,

目前遇到抽取到静态工具类的静态方法去控制展示,无法展示

.controler 只能在conponent下展示,请问有什么好的办法抽取弹窗的业务逻辑么,

要不首页的代码太多了

2 回复

可以使用自定义弹窗实现,链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-promptaction-V5#promptactionopencustomdialog11

//index
import { GlobalContext } from './GlobalContext';
import { testPromptDialog } from './Util';

@Entry
@Component
struct Index {
  aboutToAppear(): void {
    GlobalContext.getContext().setObject('UIContext', this)
  }
  build() {
    Row() {
      Column() {
        Button("promptAction弹窗")
          .onClick(() => {
            testPromptDialog()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

//GlobalContext 
export class GlobalContext {
  private constructor() {
  }

  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();
  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }
  getObject(value: string): Object | undefined {
    return this._objects.get(value);
  }
  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}

//Util
import { GlobalContext } from './GlobalContext';
import { promptAction } from '@kit.ArkUI';

let customDialogId: number = 0
@Builder
export function customDialogBuilder(content: String) {
  Column() {
    Text(`Tip: ${content} `).fontSize(20).height("30%")
    Text('内容').fontSize(16).height("30%")
    Row() {
      Button("确认").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
      Blank().width(50)
      Button("取消").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
    }
    .margin({ top: 30 })
  }.height(200).padding(5)
}
export function testPromptDialog() {
  const that = GlobalContext.getContext().getObject('UIContext') as UIContext;
  if (that) {
    promptAction.openCustomDialog({
      builder: customDialogBuilder.bind(that, "测试")
    }).then((dialogId: number) => {
      customDialogId = dialogId;
    })
  }
}

更多关于HarmonyOS 鸿蒙Next弹窗的controller抽取到静态类的静态方法中控制展示弹窗无法展示的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS中,鸿蒙Next弹窗的controller如果被抽取到静态类的静态方法中,可能会导致弹窗无法展示。这是因为静态方法和静态类的生命周期与UI组件的生命周期不一致。静态类在应用启动时加载,且在整个应用生命周期中保持不变,而UI组件的生命周期通常与Activity或Ability的创建和销毁相关联。

当弹窗的controller被放在静态类中时,它可能无法正确绑定到当前的UI上下文,导致弹窗无法正常展示。此外,静态方法无法直接访问非静态的UI组件或上下文信息,这可能导致在尝试展示弹窗时出现空指针异常或其他错误。

为了确保弹窗能够正常展示,最好将controller的实例与当前的UI上下文绑定,而不是将其放在静态类中。这样可以确保controller的生命周期与UI组件的生命周期同步,从而避免展示失败的问题。

回到顶部