4374

I have an EditText and a Button in my layout.

After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard when touching outside the keyboard. Can someone provide a simple example of how to achieve this?

8
  • 19
    What if you have only one EditText and several buttons, like check boxes and radios? The only place you need the keyboard is in the single EditText. How do you register to know that something else was chosen/clicked in order to hide the keyboard? Commented Jun 1, 2011 at 15:48
  • 21
    i feel stupid. I am unable to hide the keyboard on ICS. Tried all methods here and combinations of them. No way. The method to show it works, but I cant hide it no matter what windw token, hide flags, manifest settings or candles to any saints. On keyboard show I always see this: I/LatinIME( 396): InputType.TYPE_NULL is specified W/LatinIME( 396): Unexpected input class: inputType=0x00000000 imeOptions=0x00000000 Commented May 15, 2013 at 13:28
  • 5
    /** * This method is used to hide soft keyboard. * @param activity */ public void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } Commented Jan 13, 2014 at 13:30
  • this worked for me Commented Jun 20, 2014 at 12:45
  • Need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like readyandroid.wordpress.com/show-hide-android-soft-keyboard Commented May 4, 2018 at 6:09

132 Answers 132

2

For the kotlin users out there here is a kotlin extension method that has worked for my use cases:

fun View.hideKeyboard() {
 val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.hideSoftInputFromWindow(windowToken, 0)
}

put it in a file called ViewExtensions (or what have you) and call it on your views just like a normal method.

Sign up to request clarification or add additional context in comments.

Comments

2

First, you should add from the XML file add android:imeOptions field and change its value to actionUnspecified|actionGo as below

 <android.support.design.widget.TextInputEditText
 android:id="@+id/edit_text_id"
 android:layout_width="fill_parent"
 android:layout_height="@dimen/edit_text_height"
 android:imeOptions="actionUnspecified|actionGo"
 />

Then In the java class add a setOnEditorActionListener and add InputMethodManager as below

enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {

 @Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 if (actionId == EditorInfo.IME_ACTION_GO) {
 InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
 imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
 return true;
 }
 return false;
 }
});

Comments

2

This was work for me. It is in Kotlin for hiding the keyboard.

private fun hideKeyboard() {
 val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 val focusedView = activity?.currentFocus
 if (focusedView != null) {
 inputManager.hideSoftInputFromWindow(focusedView.windowToken,
 InputMethodManager.HIDE_NOT_ALWAYS)
 }
 }

Comments

2

Kotlin

class KeyboardUtils{
 
 companion object{
 fun hideKeyboard(activity: Activity) {
 val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
 var view: View? = activity.currentFocus
 if (view == null) {
 view = View(activity)
 }
 imm.hideSoftInputFromWindow(view.windowToken, 0)
 }
 }
}

Then just call it wherever you need

Fragments

KeyboardUtils.hideKeyboard(requireActivity())

Activities

 KeyboardUtils.hideKeyboard(this)

Comments

2

that's Working for me

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 if (imm.isActive())
 imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

Comments

2

An easy workaround is to just editText.setEnabled(false);editText.setEnabled(true); in your Button onClick() method.

Comments

2

This one works for me. You just need to pass the element inside it.

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

Comments

2

Hide Keyboard from an Activity

fun hideKeyboard() {
 val view = this.currentFocus
 if (view != null) {
 val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 imm.hideSoftInputFromWindow(view.windowToken, 0)
 }
}

Hide Keyboard from a Fragment

fun hideKeyboard() {
 val imm = requireActivity().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 val view = requireActivity().currentFocus
 if (view != null) {
 imm.hideSoftInputFromWindow(view.windowToken, 0)
 }
}

Hide Keyboard After User Interaction

button.setOnClickListener {
 val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 imm.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
}

Hide Keyboard Without a View Reference

fun hideKeyboard() {
 val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}

Hide Keyboard When Navigating Between Fragments or Activities

override fun onPause() {
 super.onPause()
 hideKeyboard() // Call the hide keyboard function here
}

Hide Keyboard Using an Extension Function

fun Activity.hideKeyboard() {
 val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 val view = this.currentFocus ?: View(this)
 imm.hideSoftInputFromWindow(view.windowToken, 0)
}

1 Comment

really nice answer
1

surround it with try catch, so that is keyboard is already closed, app would not crash :

try{
View view = this.getCurrentFocus();
if (view != null) { 
 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
 e.printStackTrace();
}

Comments

1

You only need to write one line inside your manifest activity tag

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

and it will work.

Comments

1

After reading all the answers above and in another post, I still didn't succeed in getting the keyboard to open automatically.

In my project I created a dialog (AlertDialog) dynamically (by programming it without or with minimum of needed XML).

So I was doing something like:

 dialogBuilder = new AlertDialog.Builder(activity);
 if(dialogBuilder==null)
 return false; //error
 inflater = activity.getLayoutInflater();
 dialogView = inflater.inflate(layout, null);
 ...

And after finishing setting-up all the views (TextView, ImageView, EditText,etc..) I did:

 alertDialog = dialogBuilder.create();
 alertDialog.show();

After playing around with all the answers I found out that most of them work IF you know WHERE to put the request... And that was the key to all.

So, the trick is to put it BEFORE the creation of the dialog: alertDialog.show() in my case, this worked like charm:

 alertDialog = dialogBuilder.create(); 
 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
 //And only when everything is finished - let's bring up the window - 
 alertDialog.show();
 //Viola... keyboard is waiting for you open and ready...
 //Just don't forget to request focus for the needed view (i.e. EditText..)

I'm quite sure this principle is the same with all windows, so pay attention to the location of your "showKeyboard" code - it should be before the window is launched.

A small request from the Android SDK dev team:

I think that all this is unnecessary as you can see thousands of programmers from all over the world are dealing with this ridiculous and trivial problem, while its solution should be clean and simple: IMHO if I get requestFocus() to an input-oriented view (such as EditText), the keyboard should open automatically, unless the user asks not-to, so, I think the requestFocus() method is the key here and should accept boolean showSoftKeyboard with default value of true: View.requestFocus(boolean showSoftKeyboard);

Hope this will help others like me.

Comments

1

Kotlin version

val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

1 Comment

Creating an extension function on Activity seems like a decent approach fun Activity.closeKeyboard() { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply { hideSoftInputFromWindow(window.decorView.windowToken, 0) } }
1

Some kotlin code:

Hide keyboard from Activity:

(currentFocus ?: View(this))
 .apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
 .hideSoftInputFromWindow(windowToken, 0) }
community wiki

Comments

1

I'm using following Kotlin Activity extensions:

/**
 * Hides soft keyboard if is open.
 */
fun Activity.hideKeyboard() {
 currentFocus?.windowToken?.let {
 (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
 ?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
 }
}
/**
 * Shows soft keyboard and request focus to given view.
 */
fun Activity.showKeyboard(view: View) {
 view.requestFocus()
 currentFocus?.windowToken?.let {
 (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
 ?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
 }
}

Comments

1

To show keyboard on application start:

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
 view.requestFocus();
 new Handler().postDelayed(new Runnable() {
 public void run() {
 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
 }
 }, 1000);

Comments

1

For Xamarin.Android:

public void HideKeyboard()
{
 var imm = activity.GetSystemService(Context.InputMethodService).JavaCast<InputMethodManager>();
 var view = activity.CurrentFocus ?? new View(activity);
 imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
community wiki

Comments

1
 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
 val view = appCompatActivity.currentFocus
 val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.hideSoftInputFromWindow(view.windowToken, 0)
 }

Comments

1

Hi This is simple if you are working with Kotlin i belive you can easily convert the code to Java too first in your activity use this function when your activity is load for example in the onCreate() call it.

fun hideKeybord (){
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText){
 inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}

}

as i mentiond call this Function in your onCreate() methode then add this android:windowSoftInputMode="stateAlwaysHidden" line to your activity in manafest.xml file Like this...

<activity
 android:name=".Activity.MainActivity"
 android:label="@string/app_name"
 android:theme="@style/AppTheme.NoActionBar"
 android:windowSoftInputMode="stateAlwaysHidden">

Comments

1

This code snippet can helped:

 final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
 if (inputMethodManager != null && inputMethodManager.isActive()) {
 if (getCurrentFocus() != null) {
 inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
 }
 }

It can be called in different methods according to need (ex. onPause, onResume, onRestart ...)

Comments

1
 //In Activity
 View v = this.getCurrentFocus();
 if (v != null) {
 InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 im.hideSoftInputFromWindow(view.getWindowToken(), 0);
 }
//In Fragment
 View v = getActivity().getCurrentFocus();
 if (v != null) {
 InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
 im.hideSoftInputFromWindow(view.getWindowToken(), 0);
 }
```

Comments

1

Here is the easiest way to hide the soft keyboard with Kotlin:

//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
 if ( currentFocus != null ) {
 val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
 imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
 }
 return super.dispatchTouchEvent( ev )
}

Comments

1

Don't forget: In system settings of smartphone is in "Input methods and Languages -> Physical keyboard -> Show OnScreen Keyboard -> On/Off". This settings "interfere" all programming solutions which are here! I had to disable/enable this settings too for complete hide/show onscreen keyboard! Because I am developing for device MC2200 I did it with "EMDK Profile manage -> Ui manager -> Virtual Keyboard state -> Show/Hide"

Comments

1

I tried this. Works well, tested on Nougat API 24.

import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
fun Activity.hideKeyboard() {
 getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Activity.showKeyboard() {
 getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Fragment.hideKeyboard() {
 requireActivity().getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Fragment.showKeyboard() {
 requireActivity().getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Activity.getInsetController() = WindowCompat.getInsetsController(window, window.decorView)

Comments

1

Try this:

Force fully the Android soft input keyboard:

Create a method in a helper class

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Comments

1

This works in a fragment with Android 10 (API 29):

val activityView = activity?.window?.decorView?.rootView
activityView?.let {
 val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
 imm?.hideSoftInputFromWindow(it.windowToken, 0)
}

1 Comment

What is that? Kotlin?
1

You can hide the keyboard in Kotlin as well using this code snippet.

 fun hideKeyboard(activity: Activity?) {
 val inputManager: InputMethodManager? = 
 activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? 
 InputMethodManager
 // Check if no view has focus:
 val v = activity?.currentFocus ?: return
 inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
 }

Comments

1

There is a new API in Android 11 called WindowInsetsController. Apps can get access to a controller from any view, by which we can use the hide() and show() methods:

val controller = view.windowInsetsController
// Show the keyboard (IME)
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())

See WindowInsetsController

Comments

1

If you set in your .xml android:focused="true", then it would not work, because it is a set like it is not changeable.

So the solution:

android:focusedByDefault="true"

Then it will set it once and can hide or show the keyboard.

Comments

0

I have tried all of solutions very much but no solution work for me, so I found my solution: You should have boolean variables like:

public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
 .getSystemService(Context.INPUT_METHOD_SERVICE);

And in a touch screen event you call:

@Override
public boolean onTouchEvent(MotionEvent event) {
 if(keyboardShowing==true){
 inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
 keyboardShowing = false;
 }
 return super.onTouchEvent(event);
}

And in EditText is in anywhere:

yourEditText.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
 yourClass.keyboardShowing = true;
 }
 });

Comments

0

Try this in Kotlin

 private fun hideKeyboard(){
 val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}

Try this in Java

 private void hideKeyboard(){
 InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.