meNiN meNiN - 9 days ago 6
Android Question

How to hide default keyboard when click on menu?

I have tried several methods for this website by inserting the code in the

onCreateOptionsMenu (Menu menu)
without success. I want to hide the keyboard when I click the menu button.

I have three EditText where I write some data, and options to insert / delete / modify a database, are on the menu, but if I click, the keyboard does not hide automatically.

I have something like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);

if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}


It only works the first time I press the menu button.

Thanks!

Answer

Move the code to onOptionsItemSelected instead

 public boolean onOptionsItemSelected(MenuItem item) {  
    .....
     if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){
         InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
     }
  return super.onOptionsItemSelected(item);
}