How to Fully Clear Text Fields in Android UI Tests (Works for Chinese Characters)
When clearTextField() fails to delete entire content—especially for Chinese characters—in Android UI automation, this article presents a custom cleartext() method that retrieves the field length and programmatically sends delete key events to reliably clear the input.
During mobile app testing I needed to verify that the content entered in an input field could be completely cleared, but the built‑in clearTextField() method only removed the first word or character, which broke when the text contained Chinese characters because the whole string could not be selected.
To solve this, I wrote a custom cleartext() method. It first obtains the current text of the target UI element, measures its length, and then issues a series of delete key events equal to that length. Depending on the cursor position, it can use either KeyEvent.KEYCODE_DEL (cursor at the end) or KeyEvent.KEYCODE_FORWARD_DEL (cursor at the start) to erase all characters.
public void cleartext() throws UiObjectNotFoundException {
String name = getUiObjextByResourceId("com.dianzhi.teacher.school:id/edit_content_change").getText();
outputNotable(name.length());
// If cursor is at the end
pressTimes(KeyEvent.KEYCODE_DEL, name.length());
// If cursor is at the beginning
pressTimes(KeyEvent.KEYCODE_FORWARD_DEL, name.length());
}The helper pressTimes method simply loops a specified number of times, sending the given key code to the device each iteration:
public void pressTimes(int keyCode, int times) {
// Press a key multiple times
for (int i = 0; i < times; i++) {
UiDevice.getInstance().pressKeyCode(keyCode);
}
}By calling cleartext() in UIAutomator scripts, the entire content of the input field—regardless of language or character set—can be reliably removed, enabling accurate validation of save operations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
