DEV Community

HarmonyOS
HarmonyOS

Posted on

How to dynamically add or remove options in a SelectDialog?

Read the original article:How to dynamically add or remove options in a SelectDialog?

Problem Description

As shown in the figure, the API reference provides the following schematic diagram: how to customize the number of radio buttons so that the content of the pop-up window's title is obtained by iterating through a string array using foreach?

cke_271.png

Background Knowledge

SelectDialog: A selection-type pop-up dialog that provides optional content in list or grid form within the dialog box.

Solution

Before opening the pop-up window, use a for loop to dynamically initialize the radioContent of SelectDialog.
Example code is as follows:

import { SelectDialog } from '@kit.ArkUI'

@Entry
@Component
struct SelectDialogDemo {
  // Array of titles
  titleList: string[] = [];
  // Initialize radioContent for SelectDialog
  radioContent: Array<SheetInfo> = [];
  // Set the default selected radio index
  radioIndex = 0;
  dialogControllerList: CustomDialogController = new CustomDialogController({
    builder: SelectDialog({
      title: 'Text Title',
      selectedIndex: this.radioIndex,
      confirm: {
        value: 'Cancel',
        action: () => {
        },
      },
      // Assign the initialized radioContent to the SelectDialog's radioContent property
      radioContent: this.radioContent
    }),
  })

  build() {
    Row() {
      Stack() {
        Column() {
          Button('Plain List Dialog')
            .width(96)
            .height(40)
            .onClick(() => {
              this.titleList.push('Text');
              this.titleList.push('TextText');
              this.titleList.push('TextTextText');
              this.titleList.push('TextTextTextText');
              this.titleList.push('TextTextTextTextText');
              this.titleList.push('TextTextTextTextTextText');

              // Assign values to radioContent
              this.titleList.forEach((value: string, index: number) => {
                let sheetInfo: SheetInfo = {
                  title: value,
                  action: () => {
                    this.radioIndex = index;
                  }
                }
                this.radioContent.push(sheetInfo)
              })
              this.dialogControllerList.open()
            })
        }.margin({ bottom: 300 })
      }
      .align(Alignment.Bottom)
      .width('100%')
      .height('100%')
    }
    .backgroundImageSize({ width: '100%', height: '100%' })
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Restrictions and Limitations

This example supports API Version 20 Release and later versions.
This example supports HarmonyOS 6.0.0 Release SDK and later versions.
This example requires DevEco Studio 6.0.0 Release or later for building and running.

Written by Recep Sadullah Yegin

Top comments (0)