Calling the builtin Undo functionality of EditText by sending Ctrl+Z

浪子不回头ぞ 提交于 2019-12-11 16:53:38

问题


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.

来源:https://stackoverflow.com/questions/54903249/calling-the-builtin-undo-functionality-of-edittext-by-sending-ctrlz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!