简体   繁体   中英

View.OnKeyListener for soft keyboard

I am using the View.OnKeyListener for EditText to do something when some special keys are pressed/touched. Here is a shorthened version of the code:

public class MyKeyListener implements View.OnKeyListener{
    // ...

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                // do some processing
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_0) {
                // do another processing
                return true;
            }
        }
    }
}

The problem is that the OnKeyListener, according to the documentation, is only guaranteed to be called when hard keyboards are used. And, indeed, I tested it on some phones where it doesn't work for soft keyboards. So I was wondering if there is something similar to this listener that would work for soft keyboards.

It's not guaranteed, you can't.

You can use a TextWatcher and attach that to any and all EditTexts.

Or, you create your own KeyboardView and force the user to use that one, then you can attach the expected listeners to it. https://developer.android.com/guide/topics/text/creating-input-method.html?hl=ja#IMEUI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM