DEV Community

HarmonyOS
HarmonyOS

Posted on

How does TextInput listen to the delete operation on the keyboard?

Read the original article:How does TextInput listen to the delete operation on the keyboard?

How does TextInput listen to the delete operation on the keyboard?

Requirement Description

When TextInput listens to onKeyEvent, no callback is received. How can we listen for the delete operation on the keyboard?

Background Knowledge

  • onWillDelete: Triggered when a delete operation is about to occur. This callback is not triggered during pre-editing deletion operations. Only supported when using the system input method.
  • onDidDelete: Triggered when the delete operation is completed. Only supported when using the system input method.

Implementation Steps

  • Solution 1: Display the input and deletion of TextInput through a Text component to listen for the delete operation of the keyboard.
  • Solution 2: Use the onWillDelete and onDidDelete callbacks to listen for the delete operation of the keyboard.

Code Snippet / Configuration

  • Solution 1:
  @Entry
  @Component
  struct TextInputCodeView {
    // Verification code
    @State code: string = '';
    // Number of digits in the verification code
    someArrayLength: number = 4;
    someArray: number[] = [];

    aboutToAppear(): void {
      this.someArray = Array.from({ length: this.someArrayLength });
    }

    build() {
      Column() {
        Stack() {
          Row() {
            ForEach(this.someArray, (item: number, index: number) => {
              // Add spacing
              if (index !== 0) {
                Blank();
                if (item) {
                } // Here, item is only displayed
              }
              // index+1: indicates the position of the input box.
              // Fill in the verification code
              if (this.code.length >= index + 1) {
                this.OneText({
                  str: this.code.substring(index, index + 1),
                  isBorder: index + 1 === this.someArray.length,
                });
              } else {
                // No verification code
                this.OneText({
                  str: '',
                  isBorder: this.code.length + 1 === index + 1
                });
              }
            }, (item: number, index: number) => JSON.stringify(index + 1) + item); // Key identifier
          }
          .width('100%');

          TextInput({ placeholder: '' })
            .width('100%')
            .height('100%')
            .maxLength(this.someArray.length)
            .caretColor(Color.Transparent)
            .fontColor(Color.Transparent)
            .borderColor(Color.Transparent)
            .backgroundColor(Color.Transparent)
            .onChange((value: string) => {
              this.code = value;
            });
        }
        .width('100%')
        .height(60);
      }
      .padding({ right: 12, left: 12, top: 80 });
    }

    // Parameters: verification code content, whether to display a border
    @Builder
    OneText(item: codeOne) {
      // Determine whether the current input box is selected and whether it has content.
      // If it's the selected one and has no content, display '|'
      Text(item.isBorder && !item.str ? '|' : item.str as string)
        .width(50)
        .height(50)
        .textAlign(TextAlign.Center)
        .fontSize(20)
        .fontColor(item.isBorder && !item.str ? '#87ceeb' : Color.Black)
        .backgroundColor('#f3f4f6')
        .borderRadius(8);
    }
  }

  // Verification code input box
  interface codeOne {
    str: string,
    isBorder: boolean
  }

Enter fullscreen mode Exit fullscreen mode
  • Solution 2:
  @Entry
  @Component
  struct Page {
    @State keyboardVisible: boolean = false;
    @State inputValue: string = '';

    @Builder
    buildCustomKeyboard() {
      Column() {
        Grid() {
          ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
            GridItem() {
              Button(item + '')
                .width(50).onClick(() => {
                this.inputValue += item;
              });
            };
          });
        }.maxCount(3).columnsGap(5).rowsGap(5).padding(3);
      }
      .height('170').width('100%').backgroundColor(Color.Green);
    }

    @Builder
    customKeyboard() {
      this.buildCustomKeyboard();
    }

    build() {
      Column({ space: 10 }) {
        TextInput({ text: this.inputValue })
          .id('Input')
          .customKeyboard(this.keyboardVisible ? this.customKeyboard : undefined)
          .onWillDelete((info: DeleteValue) => {
            let n = 0;
            console.info(`hm-->onWillDelete, n: ${n}, info: ${info}`);
            return true;
          })
          .onDidDelete((info: DeleteValue) => {
            let n = 1;
            console.info(`hm-->onDidDeleten: ${n}, info: ${info}`);
          }).width('80%')

        Button('Toggle Custom Keyboard').onClick(() => {
          this.keyboardVisible = true;
          focusControl.requestFocus('RichEditor');
        });

        Button('Switch to system keyboard').onClick(() => {
          this.keyboardVisible = false;
        });
      }.padding(16)
    }
  }
Enter fullscreen mode Exit fullscreen mode

Test Results

  • Solution 1: cke_1123.gif
  • Solution 2: cke_4044.gif

Limitations or Considerations

This example supports API Version 20 Release and above.
This example supports HarmonyOS 6.0.0 Release SDK and above.
This example requires DevEco Studio 6.0.0 Release or above for compilation and execution.

Written by Bunyamin Akcay

Top comments (0)