HarmonyOS 如何在一个class里面promptAction.openCustomDialog 一个自定义弹窗,并动态刷新弹窗里的数据

如何在一个class里面promptAction.openCustomDialog 一个自定义弹窗,并动态刷新弹窗里的数据

比如弹窗的标题是一个倒计时的时间,每秒变化等

import { LifecycleBridgeHandler, ResponseModel } from "@sinochemit/web_bridge";
import promptAction from '@ohos.promptAction'

interface Param {
  open: string | boolean;
  duration: number | string;
  style:number | string
}


export struct  PopViewManager{

  @Builder customDialogComponent(customDialogComponentId:number) {

    Column() {
      Text('弹窗').fontSize(30)
      Row({ space: 50 }) {
        Button("确认").onClick(() => {
          promptAction.closeCustomDialog(globalThis.customDialogComponentId)
        })
        Button("取消").onClick(() => {
          promptAction.closeCustomDialog(globalThis.customDialogComponentId)
        })
      }
    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
  }
  build() {
  }
}

export class OpenRecordVoiceBridgeHandler extends LifecycleBridgeHandler {
  static readonly HANDLER_NAME = "openRecordVoice";

  public customDialogComponentId: number = 0

  jsCallNative(data: string, callback: Function): void {

    const param: Param = JSON.parse(data);
    if (!param) {
      callback(ResponseModel.fail("参数错误"));
      return;
    }
    let duration = 60;
    let style = 0;
    let play = param.open
    duration = Number(param.duration)
    style = Number(param.style)
    if (play === "false" || play === false){

    }

    promptAction.openCustomDialog({
      builder: () => {
        new PopViewManager().customDialogComponent(this.customDialogComponentId)
      },
      onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
        console.info("reason" + JSON.stringify(dismissDialogAction.reason))
        console.log("dialog onWillDismiss")
        if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
          dismissDialogAction.dismiss()
        }
        if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
          dismissDialogAction.dismiss()
        }
      }
    }).then((dialogId: number) => {
      globalThis.customDialogComponentId = dialogId
      this.customDialogComponentId = dialogId
    })

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

动态刷新的弹窗只有这个uicontext的opencustomdialog支持

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

参考代码如下

import { UIContext } from '@ohos.arkui.UIContext';
import { getMyUiContext } from '../entryability/EntryAbility';
import { myTestClass } from './test';
import { ComponentContent } from "@ohos.arkui.node"
import promptAction from '@ohos.promptAction'
import { BusinessError } from '@ohos.base';
let customDialogId: number = 0

@Builder
function customDialogBuilder() {
  Column() {
    Text('Custom dialog Message').fontSize(10)
    Row() {
      Button("确认").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
      Blank().width(50)
      Button("取消").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
    }
    TextInput()
  }.height(200).padding(5).backgroundColor(Color.Yellow)
}

@Builder
function customDialogBuilderE() {
}

// @Builder
// function customDialogBuilder2() {
// Column(){
// Text('jhsabdchdabsch ').fontSize(40)
// }.backgroundColor(Color.Green)
// }

class Params {
  text: string = ""
  okCallback: () => void
  constructor(text: string, okCallback: () => void) {
    this.text = text;
    this.okCallback = okCallback
  }
}

@Builder
function buildText(params: Params) {
  Column() {
    Button('sdcbjadsbc').margin(10)
    Text(params.text)
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
      .width(300)
      .height(200)
      .borderRadius(30)
      .onClick(()=> {
        params.okCallback()
        console.info('tag------buildText click!!!!');
      })
    // TextInput().width(200)
  }.backgroundColor(Color.Yellow)
  .onClick(()=> {
    promptAction.showToast({
      message: "sjkfnjhv bhjfd"
    })
  })
  // .offset({x:0,y:16})
  .rotate({
    x: 0,
    y: 0,
    z: 1,
    centerX: '50%',
    centerY: '50%',
    angle: 300
  })
}

// @Builder
// function buildText() {
// Row() {
// Text('params.text')
// .fontSize(50)
// .fontWeight(FontWeight.Bold)
// .width(300)
// .height(300)
// .backgroundColor(Color.Grey)
// .borderRadius(30)
// .onClick(()=> {
// console.info('tag------buildText click!!!!');
// })
// }.rotate({
// x: 0,
// y: 0,
// z: 1,
// centerX: '50%',
// centerY: '50%',
// angle: 300
// })
// }

function clickAction(testCallback: () => void, message: string, newTestCallback: () => void) {
  let ctx: UIContext | null = getMyUiContext()
  let contentNode = new ComponentContent(ctx as UIContext, wrapBuilder(buildText), new Params(message, testCallback))
  let ttt: myTestClass = new myTestClass(ctx as UIContext, new Params(message, testCallback))
  if (ctx != null) {
    ttt.setBuilderNode(contentNode);
    ttt.setOptions({
      alignment: DialogAlignment.TopStart,
      // maskRect: { x: 50, y: 200, width: '100%', height: '50%' },
      // maskColor:'rgba(255, 10, 255, 0.5)',
      autoCancel:false,
      // isModel:false,
      // showInSubWindow: true,
      offset:{dx:0, dy:50},
      onWillDismiss: (dismissDialog: DismissDialogAction) => {
        console.info("tag-----reason=" + JSON.stringify(dismissDialog.reason))
        console.info("tag-----dialog onWillDismiss")
        if (dismissDialog.reason == DismissReason.PRESS_BACK) {
          dismissDialog.dismiss()
        }
        if (dismissDialog.reason == DismissReason.TOUCH_OUTSIDE) {
          dismissDialog.dismiss()
        }
      },
      onDidAppear: () => {
        console.info("tag----customDialog:onDidAppear()")
      },
      onDidDisappear: () => {
        console.info("tag----customDialog:onDidDisappear()")
      },
      onWillAppear: () => {
        console.info("tag----customDialog:onWillAppear()")
      },
      onWillDisappear: () => {
        console.info("tag----customDialog:onWillDisappear()")
      },
      transition:TransitionEffect.asymmetric(TransitionEffect.OPACITY
        .animation({ duration: 3000, curve: Curve.Sharp }).combine(TransitionEffect.scale({x: 1.5, y: 1.5}).animation({duration: 3000, curve: Curve.Sharp})),
        TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
          .combine(TransitionEffect.scale({x: 0.5, y: 0.5}).animation({duration: 100, curve: Curve.Smooth})))
    });
    ttt.openTestDialog();

    // if (contentNode != null) {
    // // ttt.closeTestDialog(new ComponentContent(ctx as UIContext, wrapBuilder(buildText), new Params('dhjsch', testCallback)))
    // ttt.closeTestDialog(contentNode)
    // }

    // ttt.openTestDialog();
    setTimeout(() => {
      // ttt.openTestDialog()
      // if (contentNode != null) {
      // // ttt.closeTestDialog(new ComponentContent(ctx as UIContext, wrapBuilder(buildText), new Params('dhjsch', testCallback)))
      // ttt.closeTestDialog(contentNode)
      // }
      if (contentNode != null) {
        ttt.updateTestDialog(new Params('NEW NEW NEW NEW', newTestCallback));
      }
      // if (contentNode != null) {
      // // ttt.updateDialogOptions(new ComponentContent(ctx as UIContext, wrapBuilder(buildText), new Params('dhjsch', testCallback)), {alignment: DialogAlignment.BottomEnd, showInSubwindow: false})
      // ttt.updateDialogOptions(contentNode, {}) //默认值
      // }
    }, 2500)
  }
}

@Entry
@Component
struct Index {
  @State message: string = "hello"
  testCallback() {
    console.info('tag-------testCallback!!!')
  }
  newTestCallback() {
    console.info("tag-----dialog newTestCallback!!!!!!");
  }

  build() {
    Row() {
      Column() {
        Column() {
          Text(this.message)
            .fontSize(50)
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              clickAction(this.testCallback, this.message, this.newTestCallback)
            })
        }
        .width('100%')

        Column() {
          Text(this.message)
            .fontSize(50)
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              promptAction.openCustomDialog({
                builder: customDialogBuilder.bind(this),
                // alignment: DialogAlignment.Default,
                // maskRect: { x: 50, y: 200, width: '100%', height: '50%' },
                showInSubWindow:true,
                // isModal:false,
                // borderWidth: 10,
                // borderColor: Color.Red,
                // borderStyle: BorderStyle.Dotted,
                // maskColor:Color.Green,
                // onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
                // console.info("reason" + JSON.stringify(dismissDialogAction.reason))
                // console.log("dialog onWillDismiss")
                // if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
                // dismissDialogAction.dismiss()
                // }
                // if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
                // dismissDialogAction.dismiss()
                // }
                // }
              }).then((dialogId: number) => {
                customDialogId = dialogId
              }).catch((error: BusinessError) => {
                let message = (error as BusinessError).message
                let code = (error as BusinessError).code
                console.error(`tag------promptAction.openCustomDialog args error code is ${code}, message is ${message}`);
              })
            })
        }
        .width('100%')


        Button('AlertDialog Set Duration')
          .onClick(()=>{
            AlertDialog.show(
              {
                title: 'AlertDialog 1',
                message: 'Set Animation Duration open 3 second, close 100ms',
                autoCancel: true,
                alignment: DialogAlignment.Top,
                offset: { dx: 0, dy: -20 },
                gridCount: 3,
                transition:TransitionEffect.asymmetric(TransitionEffect.OPACITY
                  .animation({ duration: 3000, curve: Curve.Sharp }).combine(TransitionEffect.scale({x: 1.5, y: 1.5}).animation({duration: 3000, curve: Curve.Sharp})),
                  TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
                    .combine(TransitionEffect.scale({x: 0.5, y: 0.5}).animation({duration: 100, curve: Curve.Smooth}))),
                confirm: {
                  value: 'button',
                  action: () => {
                    console.info('Button-clicking callback')
                  }
                },
                cancel: () => {
                  console.info('Closed callbacks')
                }
              }
            )
          })


        TextInput().width(400).margin({top:300})
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}



// // xxx.ets
// @Entry
// @Component
// struct CalendarPickerExample {
// private selectedDate: Date = new Date()
// build() {
// Column() {
// Text('月历日期选择器').fontSize(30)
// Column() {
// CalendarPicker({ hintRadius: 10, selected: this.selectedDate })
// .edgeAlign(CalendarAlign.END)
// .textStyle({ color: "#ff182431", font: { size: 20, weight: FontWeight.Normal } })
// .margin(10).offset({x:80,y:80})
// .onChange((value) => {
// console.info("CalendarPicker onChange:" + JSON.stringify(value))
// })
//
//
// CalendarPicker({ hintRadius: 10, selected: this.selectedDate }).scale({ x: 3, y: 2 })
// .edgeAlign(CalendarAlign.END)
// .textStyle({ color: "#ff182431", font: { size: 20, weight: FontWeight.Normal } })
// .margin(100)
//
//
// TextInput().width(200).height(100)
// // .scale({ x: 3, y: 2 })
// }.width("100%")
// }.width('100%')
// }
// }


import { UIContext } from '@ohos.arkui.UIContext';
import { ComponentContent } from "@ohos.arkui.node";
import { BusinessError } from '@ohos.base';

export class myTestClass {
  ctx: UIContext;
  myNode: ComponentContent<Object>;
  params: Object
  options: Object
  constructor(context: UIContext, obj?: Object) {
    this.ctx = context;
    this.params = obj
  }
  setCtx(context) {
    this.ctx = context;
  }
  getCtx() {
    return this.ctx;
  }
  setBuilderNode(node: ComponentContent<Object>) {
    this.myNode = node;
  }
  setOptions(opts: Object) {
    this.options = opts
  }
  openTestDialog() {
    console.error("lyly111----"+this.ctx);
    if (this.myNode != null) {
      // try {
      // // console.error("lyly111----", Object.keys(this.ctx));
      // console.error("lyly111----", Object.keys(this.ctx || {a: 1}));
      // } finally {
      //
      // }
      // if (this.ctx == null || this.ctx == undefined) {
      // console.error("lyly------ctx null");
      // } else {
      // if (this.ctx.getPromptAction() == null || this.ctx.getPromptAction() == undefined) {
      // console.error("lyly------getPromptAction null");
      // }
      // }
      // this.ctx.getPromptAction().showToast({message:'sdahcdshafcbhjsah'})
      this.ctx.getPromptAction().openCustomDialog(this.myNode, this.options)
        .then(()=> {
          console.info('tag------openCustomDialog complete!!!');
        }).catch((error: BusinessError) => {
        let message = (error as BusinessError).message
        let code = (error as BusinessError).code
        console.error(`tag------openCustomDialog args error code is ${code}, message is ${message}`);
      })
    }
  }
  updateTestDialog(params:Object) {
    this.myNode.update(params)
  }
  updateDialogOptions(node: ComponentContent<Object>, opts: Object) {
    if (node != null) {
      this.ctx.getPromptAction().updateCustomDialog(node, opts)
        .then(()=> {
          console.info('tag------updateCustomDialog complete!!!');
        }).catch((error: BusinessError) => {
        let message = (error as BusinessError).message
        let code = (error as BusinessError).code
        console.error(`tag------updateCustomDialog args error code is ${code}, message is ${message}`);
      })
    }
  }
  closeTestDialog(node: ComponentContent<Object>) {
    if (node != null) {
      this.ctx.getPromptAction().closeCustomDialog(node)
        .then(()=> {
          console.info('tag------closeCustomDialog complete!!!');
        }).catch((error: BusinessError) => {
        let message = (error as BusinessError).message
        let code = (error as BusinessError).code
        console.error(`tag------closeCustomDialog args error code is ${code}, message is ${message}`);
      })
    }
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
promptAction.openCustomDialog 自定义弹窗
366浏览 • 1回复 待解决
如何在全局实现一个自定义dialog弹窗
2851浏览 • 1回复 待解决
如何快速开发出一个自定义弹窗
410浏览 • 1回复 待解决
promptAction.openCustomDialog 全局弹窗
504浏览 • 1回复 待解决
ArkTS如何实现一个底部弹窗
849浏览 • 1回复 待解决