9

How to clear focused Edit text using shell command.

I tried

adb shell input keyevent KEYCODE_CLEAR // Not worked 
adb shell input keyevent KEYCODE_DEL // Delete only one char
adb shell input keyevent KEYCODE_FORWARD_DEL // Not worked

With this I am only able to delete upto One character only, Is there any way I can delete/clear the focused Edit text.

Krishnakant
  • 1,453
  • 3
  • 18
  • 30

5 Answers5

15

This works for me:

function clear_input() {
    adb shell input keyevent KEYCODE_MOVE_END
    adb shell input keyevent --longpress $(printf 'KEYCODE_DEL %.0s' {1..250})
}

Then:

clear_input
Pedro Rodrigues
  • 1,662
  • 15
  • 19
  • What are KEYCODE_MOVE_END and KEYCODE_DEL? – m0skit0 Nov 19 '19 at 11:31
  • 1
    KEYCODE_MOVE_END = move the cursor to the end of line – Pedro Rodrigues Nov 21 '19 at 08:12
  • KEYCODE_DEL = delete the character in the current cursor position – Pedro Rodrigues Nov 21 '19 at 08:12
  • 1
    I think that is not obvious and that is correct syntax because it is a constant and not an environment variable: https://developer.android.com/reference/android/view/KeyEvent – Pedro Rodrigues Nov 22 '19 at 04:04
  • I already upvoted and used your answer, but I'm just commenting to improve it. That is incorrect Bash syntax, period. Constants/variables in Bash are declared without $ but to get their value you need to prefix them with $. But hey, be my guest and avoid learning something ;) – m0skit0 Nov 22 '19 at 22:56
  • Man, those values are constants of Android SDK, not BASH. Please, take a look at the link this time. https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_MOVE_END – Pedro Rodrigues Nov 23 '19 at 02:06
5

This will select all and then backspace.

input keycombination 113 29 && input keyevent 67
4

You can use this way:

adb shell input keyevent --longpress 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67

67 is the keycode of KEYCODE_DEL

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
2

If you use uiautomator(https://github.com/xiaocong/uiautomator), you could do this by:

  1. tap the EditText widget to get focus, then

  2. use device(focused=True).clear_text() to clear the view, or by device(focused=True).set_text("new text") to set a new text.

Pang
  • 9,564
  • 146
  • 81
  • 122
J. MA
  • 29
  • 3
1

The only way that I have found so far is to get the proper coordinates to use input swipe x y x y duration to simulate a long press. This will then highlight all the text in the EditText field. You can then send the keys you want to replace what was there.

I just wish that adb shell input keyevent KEYCODE_CLEAR would clear all the text in the field. That would make things so much easier, if someone can find a better way that would be great.