简体   繁体   中英

Stop keyboard from closing when Enter is pressed in EditText?

I have an EditText which has the singleLine attribute set to true. When I press Enter on the keyboard, the keyboard is hidden. Is it possible to prevent this?

I've been using OnKeyListener which caused this problem. Switching to OnEditorActionListener stops the Keyboard from closing when pressing Enter and allows me to have full control of it.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE) {
                //DO THINGS HERE
                return true;
            }
            return false;
        }
    });

this should help you

 youredittext.setOnEditorActionListener(new OnEditorActionListener() {

    @Override
    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
         if ( (event.getAction() == KeyEvent.ACTION_DOWN  ) &&
             (keyCode           == KeyEvent.KEYCODE_ENTER)   )
        {               
           // hide virtual keyboard
           InputMethodManager imm = 
              (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
           imm.showSoftInputFromInputMethod(edittext.getWindowToken(), 0);
           return true;
        }
        return false;
    }
});

when you press the enter key the inputMethodManager will show the keyboard, if needed.

hope this will solve your problem :)

edit: if this will not work try use the event.getKeyCode() in the secend part of the if statment edit II: sorry, i read it wrong, i fixed it now try this one.

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