Calling the builtin Undo functionality of EditText

2019-08-31 22:50发布

I'm trying to execute the builtin Undo functionality of Android EditText (via TextView) by sending Ctrl+Z:

public static KeyEvent keyEvent(int keycode, int metaState) {
    final long currentTime = System.currentTimeMillis();
    return new KeyEvent(currentTime, currentTime, KeyEvent.ACTION_DOWN, keycode, 0, metaState);
}

mEditText.dispatchKeyEvent(keyEvent(KeyEvent.KEYCODE_Z, KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON));

However, it does not work (doesn't do anything). If I connect a Bluetooth keyboard and type Ctrl+Z, it works, and undo is performed in the Edit Text.

Also, sending just the letter z, without Ctrl, works, and adds a z character in the edit text:

mEditText.dispatchKeyEvent(keyEvent(KeyEvent.KEYCODE_Z, 0));

I've also tried (based on this answer and comments):

mEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_CTRL_LEFT));
mEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X));
mEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_X));
mEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_CTRL_LEFT));

but it just adds the z character to the edit text.

0条回答
登录 后发表回答