how to hide keyboard programmatically in android code example

Example 1: android hide keyboard

public void hideKeyboard(Context context, View view) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

// call from inside an Activity...
hideKeyboard(this, view);
hideKeyboard(this, getCurrentFocus());
hideKeyboard(this, getWindow().getDecorView());
hideKeyboard(this, findViewById(android.R.id.content));

Example 2: How to programmatically hide Android soft keyboard

private void closeSoftKeyboard() 
    { 
    	//If using a fragment use getActivity().getCurrentFocus()
        View v = this.getCurrentFocus(); 
  
  		// If Soft Keyboard is visible, it will be hide
        if (v != null) { 
          //If using a fragment use getActivity().getSystemService(...)
            InputMethodManager inputManager 
                = (InputMethodManager) 
                    getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); 
        } 
    }

Tags:

Java Example