目录

Custom Keyboard

Overview

The custom keyboard is a simple keyboard that is an alternative for the system default keyboard. It allows users to adjust the keyboard layout and position and add additional function keys based on actual service scenarios and habits, making user input more convenient and comfortable and improving user experience. In addition, the custom keyboard can enhance the security of user input and prevent sensitive information from being intercepted or disclosed.

This section describes how to implement and use the custom keyboard from the following aspects:

Implementation of the Custom Keyboard

The following steps are included:

[h2]Custom Keyboard Layout Implementation

The layout of the custom keyboard is displayed as a custom component, and is implemented by developers based on specific service scenarios. The height of the custom keyboard is specified by height settings of the root node of the custom component. The width cannot be set and is the screen width by default.

@Component
export struct CustomKeyboard {
  // ...
  build() {
    Column() {
      // ...
    }
    // ...
    .height(this.getKeyboardHeightVp())
    // ...
  }
}

The following is an example of implementing the numeric keyboard layout using the Grid component.

Figure 1

@Component
export struct NumberKeyboard {
  @Consume inputText: string;
  @Consume keyboardController: KeyboardController;
  layoutOptions: GridLayoutOptions = {
    regularSize: [1, 1],
    irregularIndexes: [14, 16],
    onGetIrregularSizeByIndex: (index: number) => {
      if (index === 14) {
        return [2, 1];
      }
      return [1, 2];
    }
  };

  build() {
    Grid(undefined, this.layoutOptions) {
      ForEach(numberKeyboardData, (item: Menu) => {
        GridItem() {
          Button(item.text, { type: ButtonType.Normal })
            .fontColor(Color.Black)
            .backgroundColor(item.backgroundColor)
            .borderRadius(Constants.KEYBOARD_BUTTON_RADIUS)
            .fontSize(Constants.KEYBOARD_BUTTON_FONTSIZE_18)
            .padding(0)
            .width(item.width)
            .height(item.height)
            .onClick(() => {
              this.inputText = this.keyboardController.onInput(item.text);
            })
        }
      }, (item: Menu) => JSON.stringify(item))
    }
    .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
    .rowsGap($r('app.float.number_keyboard_grid_gap'))
    .columnsGap($r('app.float.number_keyboard_grid_gap'))
  }
}

[h2]Binding Input Components to the Custom Keyboard Layout

Input components (TextArea, TextInput, RichEditor, and Search) can be bound to a custom keyboard layout using customKeyboard. After binding, the system keyboard is not started when an input component obtains the focus. Instead, the specified custom keyboard is loaded. The following implements the effect using the TextInput component.

Figure 2

The sample code is as follows:

  build() {
    Column() {
      TextInput({
        placeholder: 'Bind Custom Keyboard',
        text: this.inputText,
        controller: this.textInputController
      })
        // ...
        .customKeyboard(this.isCustomKeyboardAttach ? this.customKeyboard() : null)
          // ...
    }
  }
  @Builder
  customKeyboard() {
    CustomKeyboard()
  }
}

[h2]Listening for Keyboard Pop-up and Dismissal

In the input component, use @Link and @Watch('onChangeKeyboard') to decorate isKeyboardShown.

When the keyboard status changes, the onChangeKeyboard function is called. In this case, if you want to collapse the keyboard, the stopEditing function of the text input controller bound to the keyboard is called.

@Component
export struct TextInputComponent {
  // ...
  @Link @Watch('onChangeKeyboard') isKeyboardShown: boolean;
  // ...
  onChangeKeyboard() {
    if (this.isKeyboardShown === false) {
      this.textInputController.stopEditing();
    }
  }

  // ...
}

Two events are available for the input component.

onFocus indicates that the input component gains focus. When a user taps the input component, the input component gains focus and triggers the keyboard to pop up. In this case, if isKeyboardShown is set to true, the keyboard is shown.

onBlur represents losing focus. In this case, if isKeyboardShown is set to false, the keyboard is dismissed.

.onBlur(() => {
  this.isKeyboardShown = false;
  // ...
})
.onFocus(() => {
  this.isKeyboardShown = true;
  // ...
})

Bind isKeyboardShown with TextInputComponent bidirectionally to listen for the isKeyboardShown change and respond to keyboard pop-up and dismissal.

@Entry
@Component
struct MainPage {
  // ...
  @State isKeyboardShown: boolean = false;
  // ...
  build() {
    Navigation() {
      Column() {
        // ...
      }
      // ...
    }
    .onClick(() => {
      if (this.isKeyboardShown) {
        this.isKeyboardShown = false;
      }
    })
    .mode(NavigationMode.Stack)
    .titleMode(NavigationTitleMode.Full)
    .title($r('app.string.main_page_title'))
  }
}

Setting the Keyboard Height During Orientation Switching

Listen for screen orientation changes and calculate the keyboard height in real time in the CustomKeyboard.ets component file.

Import @ohos.display and add @State isLandscape to store the current orientation.

Register the listener display.on('change') in aboutToAppear, and unregister the listener in aboutToDisappear. When the orientation changes, updateOrientation() is called to detect the landscape mode by verifying if width > height via display.getDefaultDisplaySync().

@Component
export struct CustomKeyboard {
  // ...

  aboutToAppear(): void {
    this.updateOrientation();
    try {
      display.on('change', this.onDisplayChange);
    } catch (e) {
    }
  }

  aboutToDisappear(): void {
    try {
      display.off('change', this.onDisplayChange);
    } catch (e) {
    }
  }

  private updateOrientation() {
    try {
      const d = display.getDefaultDisplaySync();
      this.isLandscape = d.width > d.height;
    } catch (e) {
      this.isLandscape = false;
    }
  }
  // ...
}

Override getKeyboardHeightVp() to set the keyboard height ratio. The keyboard takes up 33% of the screen height in landscape mode and 22% in portrait mode on tablets, while it is fixed at 36% of the screen height on smartphones.

@Component
export struct CustomKeyboard {
  // ...

  private getKeyboardHeightVp(): number | Resource {
    try {
      const d = display.getDefaultDisplaySync();
      const ui = this.getUIContext();
      const screenHeightVp = ui.px2vp(d.height);
      const shortSideVp = ui.px2vp(Math.min(d.width, d.height));
      const isLargeScreen = shortSideVp >= 600;
      const ratio = isLargeScreen
          ? (this.isLandscape ? 0.33 : 0.22)
          :  0.36;
  
      return Math.floor(screenHeightVp * ratio);
    } catch (e) {
      return $r('app.float.keyboard_total_height');
    }
  }
  // ...
}

Modify the component height. Replace .height(...) with .height(this.getKeyboardHeightVp()) to calculate the keyboard height in real time.

@Component
export struct CustomKeyboard {
  // ...
  build() {
    // ...
    // ...
    .padding({ left: $r('app.float.keyboard_padding'), right: $r('app.float.keyboard_padding') })
    .height(this.getKeyboardHeightVp())
    .width('100%')
    .backgroundColor($r('app.color.keyboard_background_color'))
  }
}

[h2]Input Control of the Custom Keyboard

The custom keyboard can intercept gesture events and implement text input by modifying the state variable.

Figure 3

The following uses the English keyboard as an example to describe how to listen for the onClick event of EnglishButton and modify the state variable.

@Component
struct EnglishButton {
  @Consume inputText: string;
  // ...

  build() {
    Button({ type: ButtonType.Normal })
    // ...
    .onClick(() => {
      this.inputText = this.keyboardController.onInput(this.getEnglishText(this.item));
    })
  }
}

You can modify the state variable inputText to implement text input.

@Component
export struct TextInputComponent {
  @Provide inputText: string = '';
  // ...
  build() {
    Column() {
      TextInput({
        placeholder: 'Bind Custom Keyboard',
        text: this.inputText,
        controller: this.textInputController
      })
        // ...
    }
  }
  // ...
}

[h2]Cursor Control of the Custom Keyboard

By listening to the onTextSelectionChange lifecycle callback of the TextInput component, the initial cursor position is obtained. After text is input, the caretPosition method of TextInputController is called to set the final cursor position.

Figure 4

Obtain the cursor position:

TextInput({
  placeholder: 'Bind Custom Keyboard',
  text: this.inputText,
  controller: this.textInputController
})
  // ...
  .onTextSelectionChange((start: number, end: number) => {
    this.keyboardController.setCaretPosition(start, end);
  })
    // ...

Set the cursor position:

onChange(value: string) {
  this.text = value;
  if (this.keyboardType !== 'System') {
    this.textInputController?.caretPosition(this.targetCaretPos);
  }
}

[h2]Pop-up and Dismissal of the Custom Keyboard

By controlling the focus, the keyboard can be popped up and dismissed. For details, see Soft Keyboard Pop-up, Dismissal, and Listening Mechanisms.

You can also use the stopEditing method of TextInputController to dismiss the keyboard. In the following custom keyboard example, the custom keyboard is dismissed when the confirm button is tapped.

Figure 5

onInput(value: string | Resource): string {
  // ...

  switch (value.id) {
    // ...
    case $r('app.string.keyboardButton_finish').id:
      this.textInputController?.stopEditing();
      break;
  // ...
  }
  return this.text;
}

Switching Between the Custom Keyboard and System Keyboard

To switch between the custom keyboard and the system keyboard in the same text box, do the following:

Tap the 123 and ABC buttons on the tab bar, set this.isCustomKeyboardAttach to true, and bind TextInput to the custom keyboard. Tap the System button, set this.isCustomKeyboardAttach to false, and switch to the system keyboard.

Figure 6

TextInput({
  placeholder: 'Bind Custom Keyboard',
  text: this.inputText,
  controller: this.textInputController
})
  // ...
  .customKeyboard(this.isCustomKeyboardAttach ? this.customKeyboard() : null)

Layout Avoidance of the Custom Keyboard

[h2]Using the Custom Keyboard Avoidance Function Provided by the System

To ensure that the text box is not blocked by the custom keyboard, the system provides a capability for the text box to avoid the custom keyboard by default. Setting supportAvoidance to true in the customKeyboard attribute of the TextInput component enables this system-provided custom keyboard avoidance feature. For details about the keyboard avoidance mechanism and solutions to common problems, see Soft Keyboard Avoidance Mechanism.

Figure 7

TextInput({
  placeholder: 'Bind Custom Keyboard',
  text: this.inputText,
  controller: this.textInputController
})
  .customKeyboard(this.customKeyboard(), { supportAvoidance: true })
    // ...

The default custom keyboard avoidance function can only ensure that the text box is not blocked. However, the components below the text box may be blocked by the custom keyboard. As shown in the preceding figure, the tab bar below the text box is blocked by the custom keyboard. To solve this problem, you need to customize the keyboard avoidance function.

[h2]Implementing Custom Keyboard Avoidance

You need to listen for the onAreaChange lifecycle of the root node of the custom keyboard to obtain the height of the custom keyboard, and set the layout avoidance based on the actual scenario.

Figure 8

Listen to the onAreaChange lifecycle of the custom keyboard layout, obtain its height when it pops up via newValue.height, and calculate the layout avoidance height (avoidHeight) based on the actual service scenario.

@Component
export struct CustomKeyboard {
  // ...
  build() {
    Column() {
      // ...
    }
    .onAreaChange((oldValue: Area, newValue: Area) => {
      this.customKeyboardHeight = Number(newValue.height);
      let avoidHeight: number = (this.isCustomKeyboardAttach ? this.customKeyboardHeight : this.systemKeyboardHeight)
        - this.bottomRectHeight;
      this.keyboardController.changeAvoidHeight(avoidHeight);
    })
    // ...
  }
}

Send a notification of the custom keyboard height change via emitter.

changeAvoidHeight(value: number) {
  let event: emitter.InnerEvent = {
    eventId: Constants.AVOID_EVENT_ID
  };
  let eventData: emitter.EventData = {
    data: {
      'avoidHeight': value
    }
  };
  emitter.emit(event, eventData);
}

After receiving the height change notification, set the page avoidance height based on the actual service scenario.

@Entry
@Component
struct MainPage {
  @State bottomPadding: number = 210;
  @State isKeyboardShown: boolean = false;
  aboutToAppear(): void {
    let event: emitter.InnerEvent = {
      eventId: 1
    }
    emitter.on(event, (eventData: emitter.EventData) => {
      if (eventData.data) {
        let avoidHeight: number = eventData.data['avoidHeight'];
        if (avoidHeight === 0) {
          this.bottomPadding = 210;
        } else {
          this.bottomPadding = avoidHeight;
        }
      }
    })
  }
  build() {
    Navigation() {
      Column() {
        // ...
      }
      .padding({ bottom: this.bottomPadding })
      // ...
    }
    .onClick(() => {
      if (this.isKeyboardShown) {
        this.isKeyboardShown = false;
      }
    })
    .mode(NavigationMode.Stack)
    .titleMode(NavigationTitleMode.Full)
    .title($r('app.string.main_page_title'))
  }
}

Anti-Screenshot of the Custom Keyboard

When a user enters sensitive information through the custom keyboard, screenshot can be disabled to prevent illegal access, thereby protecting user privacy.

Sample Code