Search code examples
androidandroid-edittextkeyboardandroid-softkeyboardkeyboard-events

Calling the keyboard delete/backspace action on a button?


Is there a way to put the keyboard backspace action on the button or will I have to do it custom?


Solution

  • We can use Instrumentation class to simulate a Keyevent with code.

    in kotlin

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

    I just test it and worked on my emulator (API 29)

    Notice: Instrumentation can not be called in main-thread


    so you may do this below

    in Kotlin

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

    in Java

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

    KeyEvent.KEYCODE_DEL = BackSpace

    KeyEvent.KEYCODE_FORWARD_DEL = Delete


    Update example

    let me show you a snippet

    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