The soft keyboard is an important way for users to interact with the system, but its appearance and dismissal can disrupt UI element positioning, leading to the following common adaptation issues:
This article describes the following knowledge to help you understand the control of soft keyboard pop-up and dismissal, avoidance mechanisms, and solutions to common soft keyboard issues.
When a user taps a text box, the soft keyboard is displayed by default. In certain scenarios, you need to control the pop-up and dismissal of the soft keyboard, for example, dismissing the soft keyboard when a user taps a blank area or automatically focusing the text box when a user accesses a page. You also need to adjust the page layout based on the soft keyboard status and height.
When accessing a page, a user expects that the text box on the page can be actively focused and the soft keyboard pops up automatically for information input. For example, when a user taps the search box on the app home page to access the search page, the soft keyboard pops up, as shown in the figure below.

You can implement this by setting defaultFocus of the text box to true.
TextInput() .defaultFocus(true)
You can use the requestFocus() method of FocusController to move the focus to the corresponding entity node on the component tree based on the component ID and display the soft keyboard. For example, when the emoji panel is switched to text input, the system soft keyboard is displayed upon taps on the emoji icon.

The sample code is as follows:
TextInput({ placeholder: 'Please enter a contact name' })
.id('input1')
Button('login')
.onClick(() => {
this.getUIContext().getFocusController().requestFocus('input1');
})
Before calling requestFocus, ensure that the TextInput component has been mounted. Do not call requestFocus when the component is not created.
Call the clearFocus() method of FocusController to dismiss the soft keyboard. For example, when a user taps the Search button, the soft keyboard is hidden, as shown in the figure below.

The sample code is as follows:
Button('Search')
.onClick(() => {
this.getUIContext().getFocusController().clearFocus();
}) You can also dismiss the keyboard using stopEditing(), which requires binding the text box to a TextInputController. However, this becomes cumbersome with multiple text boxes, as each would need its own TextInputController. In this case, you are advised to remove the focus via clearFocus().
@Component
struct StopEditingCpt {
private controller: TextInputController = new TextInputController();
build() {
Column() {
TextInput({ placeholder: 'Input', controller: this.controller })
Button('Search')
.onClick(() => {
this.controller.stopEditing();
})
}
}
} You can adjust component positions to adapt to the UI or display/hide some components by leveraging the soft keyboard height obtained and its pop-up state detected through listeners. Use the on('keyboardHeightChange') method of the window module to listen for height changes of the soft keyboard and obtain the height of the soft keyboard in real time. In the following example, the emoji bar is displayed after the soft keyboard pops up, and is hidden with the soft keyboard.

Call the on('keyboardHeightChange') method to obtain the soft keyboard height in real time (the return value is an integer, in pixels) and assign this value to the variable keyboardHeight. If the value of keyboardHeight is 0, the soft keyboard and the emoji bar are both hidden. If the value of keyboardHeight is not 0, the soft keyboard and the emoji bar are both displayed. The sample code is as follows:
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct GetKeyboardHeightDemo {
@State keyboardHeight: number = 0; // Soft keyboard height
aboutToAppear(): void {
try {
window.getLastWindow(this.getUIContext().getHostContext()).then(currentWindow => {
currentWindow.on('keyboardHeightChange', (data: number) => {
this.keyboardHeight = this.getUIContext().px2vp(data);
})
})
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'GetKeyboardHeightDemo',
`getLastWindow failed, error code=${err.code}, message=${err.message}`);
}
}
build() {
Column() {
// ...
TextInput()
if (this.keyboardHeight > 0) {
Row() { // Emoji
// ...
}
// ...
}
}
}
} You can use the on('avoidAreaChange') method of the window module to listen for changes of the system avoid area in the current window to obtain the visible content area size, and listen for the soft keyboard pop-up and dismissal events. Dynamically adjust the height of the components in the layout to adapt to the UI based on the visible area size after the soft keyboard pops up. For details, see Listening for Soft Keyboard Pop-up Events to Implement Avoidance in FAQs.
import { KeyboardAvoidMode, window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct GetSafeAreaHeightDemo {
@State screenHeight: number = 0; // The height of the safe area
@State isKeyBoardHidden: boolean = false; // Whether the soft keyboard is hidden
aboutToAppear(): void {
try {
window.getLastWindow(this.getUIContext().getHostContext()).then(currentWindow => {
let property = currentWindow.getWindowProperties();
let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD);
// Initialize the display area height
this.screenHeight = this.getUIContext()
.px2vp(property.windowRect.height - avoidArea.topRect.height - avoidArea.bottomRect.height);
// Enables the monitoring of changes in the avoidance zone of the current window
currentWindow.on('avoidAreaChange', data => {
if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) {
return;
}
if (data.area.bottomRect.height <= 0) {
this.isKeyBoardHidden = true;
} else {
this.isKeyBoardHidden = false;
}
this.screenHeight = this.getUIContext()
.px2vp(property.windowRect.height - data.area.topRect.height - data.area.bottomRect.height);
hilog.info(0x0000, 'GetSafeAreaHeightDemo', `screen height is: ${this.screenHeight}`);
})
})
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'GetSafeAreaHeightDemo',
`getLastWindow failed, error code=${err.code}, message=${err.message}`);
}
}
build() {
Column() {
TextInput()
}
}
} To address the UI adaptation issue of the soft keyboard, you need to understand the avoidance mechanism of the soft keyboard in HarmonyOS.
The soft keyboard avoids the text box by default in the system. The following describes the main avoidance effects based on the text box list.

By default, the system executes the security avoidance policy for the text box position to ensure that the text box is not blocked by the soft keyboard.
Description |
| If the current text box is blocked by the soft keyboard, the components are lifted to display the complete text box just above the soft keyboard. The components above the text box are lifted accordingly, and the components below the text box are not displayed. You can see in the following right figure that TextInput 12 is invisible. |
|---|---|---|
Effect |
|
|
Rules for avoiding text boxes in dialog boxes
Dialog box avoidance can be configured via BaseDialogOptions by setting the KeyboardAvoidMode. When using the default avoidance mode (Default), if the soft keyboard pops up and covers the text box, the entire dialog box will lift upward. To enhance UX aesthetics, a default spacing of 16 vp is applied.

The default soft keyboard avoidance mode ensures that the text box is not blocked, but components below the text box may be blocked by the soft keyboard. To address this issue, it is necessary to understand the soft keyboard's avoidance modes.
When a user inputs information, the system provides the avoidance modes to ensure that the text box is not blocked by the keyboard. You can use setKeyboardAvoidMode to control the avoidance mode of the page when the virtual keyboard appears. The default avoidance mode is OFFSET, which lifts the entire page content. The following lists several common avoidance modes.
import { KeyboardAvoidMode, window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/GetSafeAreaHeightDemo', (err) => {
// Lift up mode
windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.OFFSET);
});
}
} The effect is as follows, where the entire page is lifted to avoid the soft keyboard.

export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/GetSafeAreaHeightDemo', (err) => {
// Compression mode
windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
});
}
} The effect is as follows, where the content area is compressed to avoid the soft keyboard.

aboutToAppear(): void {
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.NONE);
}
Caret avoidance
There are two modes for caret avoidance: KeyboardAvoidMode.OFFSET_WITH_CARET and KeyboardAvoidMode.RESIZE_WITH_CARET. When the caret position in the text box changes, the system automatically triggers the corresponding UI avoidance actions to ensure the caret remains visible at all times. For details, see Implementing Caret Avoidance.
Dialog avoidance
Dialog components (Dialog, Popup, Menu, and BindSheet) have two avoidance modes: KeyboardAvoidMode.DEFAULT and KeyboardAvoidMode.NONE. You can set the keyboardAvoidMode property in BaseDialogOptions to flexibly control whether to avoid the soft keyboard.
If the avoidance mode is not specified, the dialog box follows the avoidance mode of the page. For example, if you set the avoidance mode to KeyboardAvoidMode.NONE, the dialog box will not avoid the soft keyboard.
this.getUIContext().getPromptAction().openCustomDialog({
builder: () => {
this.customDialogBuilder();
},
alignment: DialogAlignment.Bottom,
width: '100%',
// Set not avoid keyboard
keyboardAvoidMode: KeyboardAvoidMode.NONE,
}); In the avoidance modes described above, components are moved to avoid the soft keyboard. However, there are cases where you might want components to not avoid the soft keyboard—for example, keeping the top title bar stationary in OFFSET mode. To meet this requirement, you need to learn about the safe area and the expandSafeArea property.
The expandSafeArea property is used to extend the drawing area of the component beyond the safe area without changing the layout. When type of the expandSafeArea property is set to SafeAreaType.KEYBOARD, that is, expandSafeArea ([SafeAreaType.KEYBOARD]), the system regards the soft keyboard area as a safe area and components do not avoid it. The custom title bar is fixed when the page is lifted due to the pop-up of the soft keyboard. For details, see the example in Layout Misplacement.

In the following example, the email page consists of a title bar, a content area, and an operation bar at the bottom. When a user taps the text box, the soft keyboard blocks the bottom operation bar, undermining user experience, as shown in the figure below.

The height of the title bar and operation bar is fixed to 56, and the height of the content area is layoutWeight(1), which is an adaptive height. The sample code is as follows:
@Component
export struct MailPage {
// ...
build() {
Column() {
this.NavigationTitle()
this.EmailContent()
this.BottomToolbar()
}
// ...
}
@Builder
NavigationTitle() {
Row() {
// ...
}
.width('100%')
.height("56vp")
// ...
}
@Builder
BottomToolbar() {
Row({ space: 12 }) {
// ...
}
.width('100%')
.height("56vp")
// ...
}
@Builder
EmailContent() {
Column() {
// ...
}
.width('100%')
.layoutWeight(1)
// ...
}
} You can set the avoidance mode of the soft keyboard to KeyboardAvoidMode.RESIZE to prevent the operation bar from being blocked. After this property is set, the avoidance of the soft keyboard is implemented by resizing the height of the content area. The sample code is as follows:
aboutToAppear(): void {
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
}
aboutToDisappear(): void {
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.OFFSET);
} Note that the height of the content area must be set in percentage. The following figure shows the effect.

Listening for soft keyboard pop-up events to implement avoidance
In the preceding example, you can also use the getWindowAvoidArea method of the window module to listen for the soft keyboard pop-up events and obtain the height of the safe area to dynamically set the page height. The sample code is as follows:
import { CommonConstants as Const } from '../common/constants/CommonConstants';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct MailHomePage2 {
@State message: string = 'Hello World';
@State screenHeight: number = 0;
@State isKeyBoardHidden: boolean = false;
aboutToAppear(): void {
try {
window.getLastWindow(this.getUIContext().getHostContext()).then(currentWindow => {
let property = currentWindow.getWindowProperties();
let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
// Initialize the display area height
this.screenHeight = this.getUIContext().px2vp(property.windowRect.height - avoidArea.topRect.height - avoidArea.bottomRect.height);
// Monitor the ejection and retraction of the soft keyboard
currentWindow.on('avoidAreaChange', async data => {
if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) {
return;
}
if (data.area.bottomRect.height <= 0) {
this.isKeyBoardHidden = true;
} else {
this.isKeyBoardHidden = false;
}
this.screenHeight = this.getUIContext().px2vp(property.windowRect.height - avoidArea.topRect.height - data.area.bottomRect.height);
})
})
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'MailHomePage2', `getLastWindow failed, error code=${err.code}, message=${err.message}`);
}
}
build() {
Column() {
this.NavigationTitle()
this.EmailContent()
this.BottomToolbar()
}
.width('100%')
.height(this.screenHeight) // Dynamically sets the viewport height
.expandSafeArea([SafeAreaType.KEYBOARD])
.backgroundColor('#F1F3F5')
}
// ...
} If the system's avoidance mechanism cannot meet your requirements, you can listen for the soft keyboard pop-up events and adjust the layout size and position based on the obtained height of the safe area or soft keyboard to implement avoidance.
Content scrolling up with a fixed top
Take the chat page as an example. On the top is a custom title bar, middle is a scrollable message area, and the bottom is a text box. The sample code is as follows:
@Entry
@Component
export struct ContactPage {
// ...
build() {
Row() {
Column() {
Row() {
// ...
}
// ...
.height('12%')
// ...
.expandSafeArea([SafeAreaType.KEYBOARD])
.zIndex(1)
// ...
List() {
// ...
}
.height('76%')
// ...
Column() {
// ...
}
.height('12%')
// ...
}
.width('100%')
// ...
}
.height('100%')
}
} As the offset mode is used by default, the entire page, including the title bar, is lifted, as shown in the figure below.

However, the requirement is that when the text box is tapped and the soft keyboard pops up, only the content area is lifted with the title fixed. The expected effect is as follows.

To fix the position of the title, set the .expandSafeArea([SafeAreaType.KEYBOARD]) property for the title component so that it does not avoid the soft keyboard. The sample code is as follows:
@Entry
@Component
export struct ContactPage {
// ...
build() {
Row() {
Column() {
Row() {
// ...
}
// ...
.height('12%')
// ...
.expandSafeArea([SafeAreaType.KEYBOARD])
.zIndex(1)
// ...
List() {
// ...
}
.height('76%')
// ...
Column() {
// ...
}
.height('12%')
// ...
}
.width('100%')
// ...
}
.height('100%')
}
} For details, see the sample code Keyboard.
Lifted custom dialog box affecting user experience
As described in the avoidance mechanism, the dialog box is lifted to avoid the soft keyboard, which may affect user experience. In the following example, the dialog box of the comment list is implemented using @CustomDialog. The sample code is as follows:
@CustomDialog
struct CommentDialog {
listData: string[] = ['comments1', 'comments2', 'comments3', 'comments4', 'comments5', 'comments6', 'comments7', 'comments8'];
controller?: CustomDialogController;
build() {
Column() {
Text('comments')
.fontSize(20)
.fontWeight(FontWeight.Medium)
List() {
ForEach(this.listData, (item: string) => {
ListItem() {
Text(item)
.height(80)
.fontSize(20)
}
}, (item: string) => item)
}
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
TextInput({ placeholder: 'Please input content' })
.height(40)
.width('100%')
}
.padding(12)
}
}
@Entry
@Component
struct CustomDialogDemo {
dialogController: CustomDialogController | null = new CustomDialogController({
builder: CommentDialog(),
alignment: DialogAlignment.Bottom,
cornerRadius: 0,
width: '100%',
height: '80%'
})
build() {
Column() {
Button('click me')
.onClick(() => {
if (this.dialogController !== null) {
this.dialogController.open();
}
})
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
} When a user taps the text box at the bottom of the dialog box, the dialog box is lifted as a whole, and the text box is over lifted.

To address this issue, set mode of NavDestination to NavDestinationMode.DIALOG. In this case, the entire NavDestination is displayed transparently by default. The sample code is as follows:
@Entry
@Component
struct NavDestinationModeDemo {
@Provide('NavPathStack') pageStack: NavPathStack = new NavPathStack()
@Builder
PagesMap(name: string) {
if (name === 'DialogPage') {
DialogPage()
}
}
build() {
Navigation(this.pageStack) {
Column() {
Button('click me')
.onClick(() => {
this.pageStack.pushPathByName('DialogPage', '');
})
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
.mode(NavigationMode.Stack)
.navDestination(this.PagesMap)
}
}
@Component
export struct DialogPage {
@Consume('NavPathStack') pageStack: NavPathStack;
listData: string[] = ['Comment 1', 'Comment 2', 'Comment 3', 'Comment 4', 'Comment 5', 'Comment 6', 'Comment 7', 'Comment 8'];
build() {
NavDestination() {
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Text('Comments')
.fontSize(20)
.fontWeight(FontWeight.Medium)
List() {
ForEach(this.listData, (item: string) => {
ListItem() {
Text(item)
.height(80)
.fontSize(20)
}
}, (item: string) => item)
}
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
TextInput({ placeholder: 'Please input content' })
.height(40)
.width('100%')
}
.backgroundColor(Color.White)
.height('75%')
.width('100%')
.padding(12)
}
.height('100%')
.width('100%')
}
.backgroundColor('rgba(0,0,0,0.2)')
.hideTitleBar(true)
.mode(NavDestinationMode.DIALOG)
}
} In addition, set the soft keyboard avoidance mode to RESIZE. The sample code is as follows:
import { UIAbility } from "@kit.AbilityKit";
import { window, KeyboardAvoidMode } from "@kit.ArkUI";
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/GetSafeAreaHeightDemo', (err) => {
// Compression mode
windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
});
}
} After a user taps the text box, the content area is resized, and the dialog box is not lifted. The following figure shows the effect.

For details about how to implement the effect in comment scenarios, see Comment Dialog Box.
In the default avoidance mode, there is a 16vp gap between the soft keyboard and dialog box. You can adjust this distance by setting keyboardAvoidDistance in BaseDialogOptions. Note that the value of keyboardAvoidMode should be set to KeyboardAvoidMode.DEFAULT.
this.getUIContext().getPromptAction().openCustomDialog({
builder: () => {
this.customDialogBuilder();
},
alignment: DialogAlignment.Bottom,
width: '100%',
// Set the distance between the soft keyboard and custom dialog to 0
keyboardAvoidDistance:LengthMetrics.vp(0)
}); For details about how to trigger and avoid the soft keyboard by using the text boxes within Web components, see Docking to the Soft Keyboard.