Posted By

BenClayton on 03/05/11


Tagged


Versions (?)

Android: Close soft keyboard when ENTER button pressed


 / Published in: Java
 

I kinda assumed the keyboard would automatically close when the ENTER key is pressed, but no it doesn't... Here's how..

  1. textInput = (EditText)findViewById(R.id.textInput);
  2. textInput.setInputType( InputType.TYPE_TEXT_VARIATION_URI ); // optional - sets the keyboard to URL mode
  3.  
  4. // kill keyboard when enter is pressed
  5. textInput.setOnKeyListener(new OnKeyListener()
  6. {
  7. /**
  8.   * This listens for the user to press the enter button on
  9.   * the keyboard and then hides the virtual keyboard
  10.   */
  11. public boolean onKey(View arg0, int arg1, KeyEvent event) {
  12. // If the event is a key-down event on the "enter" button
  13. if ( (event.getAction() == KeyEvent.ACTION_DOWN ) &&
  14. (arg1 == KeyEvent.KEYCODE_ENTER) )
  15. {
  16. InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
  17. imm.hideSoftInputFromWindow(textInput.getWindowToken(), 0);
  18. return true;
  19. }
  20. return false;
  21. }
  22. } );

Report this snippet  

You need to login to post a comment.