Android:Hide keyboard after button click

Martin Shinks picture Martin Shinks · Nov 27, 2012 · Viewed 65.7k times · Source

I need to hide the android keyboard after a button click.

I have seen many examples of how to do this, however, they all appear to use a specific editText object.

e.g.

InputMethodManager imm = (InputMethodManager)getSystemService(
      Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

My problem is that I am building the screen dynamically, thus there could be mane edit text fields. Is there a way the keyboard can be hidden without me having to specify which editText object I am hiding it for.

Answer

burmat picture burmat · Nov 27, 2012

You could instead set it to your layout, ie:

LinearLayout mainLayout;

// Get your layout set up, this is just an example
mainLayout = (LinearLayout)findViewById(R.id.myLinearLayout);

// Then just use the following:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mainLayout.getWindowToken(), 0);

This is an example assuming that your layout will be created regardless of how many EditText objects (or other objects) are placed on it.

Edit: Also, something I find very useful is to make sure that the keyboard is hidden when an activity first launches (ie: if an EditText is the first thing focused). To do that, I put this in onCreate() method of Activity:

 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);