HarmonyOS 全局声明自定义弹窗的控制器?

如题:HarmonyOS 全局声明自定义弹窗的控制器?

阅读 514
1 个回答

参考demo:

import { ComponentContent } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Parent {
  aboutToAppear(): void {
    //存储全局UIContext 变量
    GlobalContext.getContext().setObject('UIContext', this.getUIContext());
  }
  private customDialog = new CustomDialog()

  build() {
    Column() {
      Button("click").onClick(()=>{
        this.customDialog.openDialog()
      }).width(100).height(100)
    }
  }
}

class CustomDialog{
  openDialog(){
    let uiContext =  GlobalContext.getContext().getObject('UIContext') as UIContext
    if (uiContext) {
      let promptAction = uiContext.getPromptAction();
      let contentNode = new ComponentContent((uiContext as UIContext), wrapBuilder(buildText));
      try {
        promptAction.openCustomDialog(contentNode);
      } catch (error) {
        let message = (error as BusinessError).message;
        let code = (error as BusinessError).code;
        console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
      };
    }
  }
}

@Builder
function buildText() {
  Column() {
    Text('this is dialog')
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
      .margin({bottom: 36})
  }.backgroundColor(Color.Pink).width('100%').height('100%')
}

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 {
    console.log(typeof (this._objects.get(value)))
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}

参考链接:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-UIContext.md\#opencustomdialog12

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进