在按钮上调用键盘 delete/backspace 操作?

Calling the keyboard delete/backspace action on a button?

有没有办法将键盘退格键操作放在按钮上,或者我必须自定义吗?

我们可以使用 Instrumentation class to simulate a Keyevent 代码。

kotlin

val instrumentation = Instrumentation()
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL)

我只是测试它并在我的模拟器上工作 (API 29)

注意:Instrumentation不能在main-thread

中调用

所以你可以在下面这样做

Kotlin

thread
{
    Instrumentation()
    instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL)
{

Java

new Thread()
{
    ..
    new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
    ..
}.start();

KeyEvent.KEYCODE_DEL = 退格键

KeyEvent.KEYCODE_FORWARD_DEL = 删除


更新示例

让我给你看一个片段

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(){
                @Override
                public void run() {

                    Instrumentation instrumentation = new Instrumentation();
                    instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
                }
            }.start();
        }
    });

like this