keyListener does not recognise input

Andre :

I have a KeyListener on an editText like so:

tip = (EditText) findViewById(R.id.tip);
tip.setOnKeyListener(new EditText.OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        Log.i("debug123", "onKeyListener. event.getKeyCode(): " + event.getKeyCode());

        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            checkInput();
            return true;
        }
        return false;
    }
});

But no softkeyboard-stroke is recognised.? Only when I left the Activity with the BACK-Button (HardwareButton) the Listener recognises the action. But from all that I read, this is the way to go if I want to work with user-input at a EditText.

Md. Asaduzzaman :

setOnKeyListener

Register a callback to be invoked when a hardware key is pressed in this view. Key presses in software input methods will generally not trigger the methods of this listener.

setOnEditorActionListener

Set a special listener to be called when an action is performed on the text view. This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user.

To solve your problem using setOnEditorActionListener, please check below:

  • Add imeOptions and inputType to your EditText
<EditText
    android:id="@+id/tip"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  • Then add setOnEditorActionListener to EditText
tip.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if ( (actionId == EditorInfo.IME_ACTION_DONE) || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) ) {
            checkInput();
            return true;
        } else {
            return false;
        }
    }
});

Here,

  • actionId == EditorInfo.IME_ACTION_DONE handle action from Soft Keyboard (IME)
  • event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN handle enter key from Hardware Keyboard

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7362&siteId=1
Recommended