How Do I Close a Specified Pop-up Window When OpenCustomDialog Is Used?

Read the original article:How Do I Close a Specified Pop-up Window When OpenCustomDialog Is Used?

How Do I Close a Specified Pop-up Window When OpenCustomDialog Is Used?

Problem Description

When using openCustomDialog to create custom pop-up dialogs, if multiple dialogs are opened on the page, how can you correctly close a specified dialog?

Background Knowledge

  • In the UIContext, the getPromptAction method retrieves a PromptAction instance that provides the openCustomDialog and closeCustomDialog methods, which are used to open and close custom dialogs, respectively:
    – openCustomDialog: Opens a custom dialog that supports customizable styles, such as width, height, background color, and shadow.
    – closeCustomDialog: Closes the custom dialog.

Troubleshooting Process

  1. Reproduce the Issue:

    • Open multiple custom dialogs using openCustomDialog and attempt to close them individually.
    • Verify that the correct dialog closes when the “Close pop-up window” button is clicked.
  2. Analyze the Logic:

    • The dialogMap stores dialog IDs mapped to their respective dialog numbers.
    • When closing a dialog, the corresponding ID is retrieved from dialogMap using the dialog number.
    • The issue may arise if the dialogMap is not properly updated or if the dialog ID is incorrect.
  3. Check Dialog ID Assignment:

    • Ensure openCustomDialog returns a valid dialogId and is correctly stored in dialogMap.
    • Verify that the dialogNum is unique for each dialog and matches the key in dialogMap.
  4. Validate Close Operation:

    • Confirm that closeCustomDialog is called with the correct dialogId retrieved from dialogMap.
    • Check for potential errors in the try-catch block during closure.

Analysis Conclusion

The issue stems from improper handling of dialog IDs in dialogMap, leading to incorrect or missing IDs during closure. By ensuring accurate storage and retrieval of dialog IDs and adding error checks, the dialogs can be closed correctly.

Solution

When openCustomDialog creates and opens a pop-up window, it returns a dialogId in the callback upon successful opening of the pop-up, indicating the currently opened pop-up. This id can uniquely identify the pop-up, allowing for the use of data structures such as Map to store the opened pop-ups and their corresponding id identifiers, thereby enabling the differentiation of multiple pop-ups on the page.
The return value of promptAction.openCustomDialog is explained as follows:

Type Instructions
Promise Return the dialog ID for use by closeCustomDialog

The code example is as follows:

import { BusinessError } from '@kit.BasicServicesKit';
import { HashMap } from '@kit.ArkTS';

@Entry
@Component
struct CustomDialogDemo {
  @State dialogNum: number = 0;
  ctx: UIContext = this.getUIContext()
  dialogMap: HashMap<number, number> = new HashMap();

  @Builder
  customDialogComponent(dialogNumber: number) {
    Column() {
      Text('Pop-up window' + dialogNumber).fontSize(14)
      Row({ space: 25 }) {
        Button('Close pop-up window').onClick(() => {
          try {
            // When closing, locate the corresponding pop-up window ID to achieve the closure of the specified pop-up window.
            this.ctx.getPromptAction().closeCustomDialog(this.dialogMap.get(dialogNumber));
          } catch (error) {
            let message = (error as BusinessError).message;
            let code = (error as BusinessError).code;
            console.error(`closeCustomDialog error code is ${code}, message is ${message}`);
          }
        })
      }
    }.height('70%').padding(5).width('70%')
    .backgroundColor(Color.Pink)
    .margin({ left: dialogNumber * 10 })
  }

  build() {
    Column({ space: 20 }) {
      Text('Click to open the pop-up window')
        .fontSize(14)
        .onClick(() => {
          this.dialogNum += 1;
          this.ctx.getPromptAction()
            .openCustomDialog({
              builder: () => {
                this.customDialogComponent(this.dialogNum);
              },
              isModal: false
            })
            .then((dialogId: number) => {
              // Store the corresponding pop-up box ID
              try {
                this.dialogMap.set(this.dialogNum, dialogId);
              } catch (error) {
                console.error(`error: ${error}`)
              }
            })
            .catch((error: BusinessError) => {
              console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`);
            })
        })
    }
    .width('100%')
    .padding(30)
  }
}

Verification Result

output7.gif

Written by Emrecan Karakas

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Logtide 0.6.0: PII Masking, Keyboard Shortcuts & Anomaly Detection

Next Post

Like Stories? Love Python! 📖🐍 Ep.3

Related Posts