ItGo.me Focus on IT Recommend

Home > Close/hide the Android Soft Keyboard

Close/hide the Android Soft Keyboard

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. I assume that there's a simple, one or two-liner to make this happen.

Where can I find an example of it?

android android-softkeyboard android-keypad android-input-method soft-keyboard
|
  this question
edited Oct 27 '16 at 9:58 community wiki
11 revs, 8 users 43%
Vidar Vestnes 6   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? –  AlikElzin-kilaka Jun 1 '11 at 15:48 7   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 –  rupps May 15 '13 at 13:28 1   /** * 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.getCur‌​rentFocus().getWindo‌​wToken(), 0); } –  Harshal Benake Jan 13 '14 at 13:30      this worked for me –  nmxprime Jun 20 '14 at 12:45 13   It's very sad that such a seemingly simple question is so popular. –  lang2 Mar 21 '15 at 3:29  |  show more comments

57 Answers
57

prev 1 2
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

after that call on onTouchListener:

findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Utils.hideSoftKeyboard(activity);
        return false;
    }
});

|
  this answer
answered May 18 '13 at 4:40 community wiki
Riser      Try this as well - this worked for me: InputMethodManager imm = ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)); imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().g‌​etWindowToken(), 0); –  zmicer Nov 7 '13 at 12:20

 | 

It works for me..

EditText editText=(EditText)findViewById(R.id.edittext1);

put below line of code in onClick()

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

here hide the keyboard when we click the Button and when we touch the EditText keyboard will be display.

(OR)

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

|
  this answer
edited Jul 30 '14 at 7:34 community wiki
3 revs
Sandeep Maram

 | 
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}

|
  this answer
answered Aug 21 '14 at 11:51 community wiki
Vaishali Sutariya      good answer, but activity.getCurrentFocus() can return null –  fRoStBiT Aug 27 '14 at 15:59

 | 

For Open Keyboard :

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtView, InputMethodManager.SHOW_IMPLICIT);

For Close/Hide Keyboard :

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

|
  this answer
answered Feb 5 '15 at 12:39 community wiki
girishce26

 | 
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

|
  this answer
edited Apr 24 '15 at 21:11 community wiki
2 revs, 2 users 67%
MuhammadAamirALi      This answer is dangerous because the code can throw a NullPointerException. activity.getCurrentFocus() can return null. –  Oliver Kranz Jul 9 '15 at 15:20

 | 

Sometime you can have an activity that contains a listview with rows that contains editText so you have to setup in manifest SOFT_INPUT_ADJUST_PAN then they keyboard shows up which is annoying.

The following workarround works if you place it at the end of onCreate

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
        },100);

|
  this answer
answered Sep 27 '15 at 11:10 community wiki
Ricardo

 | 

In some cases this methods can works except of all others. This saves my day :)

public static void hideSoftKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public static void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

|
  this answer
answered Feb 4 '16 at 11:46 community wiki
iscariot

 | 

I created a layout partially from xml and partially from a custom layout engine, which is all handled in-code. The only thing that worked for me was to keep track of whether or not the keyboard was open, and use the keyboard toggle method as follows:

public class MyActivity extends Activity
{
    /** This maintains true if the keyboard is open. Otherwise, it is false. */
    private boolean isKeyboardOpen = false;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater;
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);

        setContentView(contentView);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
        {
            public void onGlobalLayout() 
            {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) 
                    isKeyboardVisible = true;
                else
                    isKeyboardVisible = false;
             });
         }
    }

    public void closeKeyboardIfOpen()
    {
        InputMethodManager imm;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isKeyboardVisible)
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }   
}

|
  this answer
answered Dec 18 '12 at 1:36 community wiki
Phil

 | 

This method will always always work at any cost. Just Use it wherever you want to hide the keyboard

public static void hideSoftKeyboard(Context mContext,EditText username){
        if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
            InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
        }
    }

Use it like this :

Whatever is the version of Android. This method will surely work


|
  this answer
answered Oct 4 '13 at 7:11 community wiki
Gaurav Arora

 | 

This worked for me.

public static void hideKeyboard(Activity act, EditText et){
    Context c = act.getBaseContext();
    View v = et.findFocus();
    if(v == null)
        return;
    InputMethodManager inputManager = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

|
  this answer
edited Apr 24 '15 at 21:12 community wiki
2 revs, 2 users 86%
moberme

 | 

Try This one

public void disableSoftKeyboard(final EditText v) {
    if (Build.VERSION.SDK_INT >= 11) {
        v.setRawInputType(InputType.TYPE_CLASS_TEXT);
        v.setTextIsSelectable(true);
    } else {
        v.setRawInputType(InputType.TYPE_NULL);
        v.setFocusable(true);
    }
}

|
  this answer
edited Apr 24 '15 at 21:13 community wiki
2 revs, 2 users 71%
Sagar Badave

 | 

In AndroidManifest.xml under <activity..> set android:windowSoftInputMode="stateAlwaysHidden"


|
  this answer
answered Dec 14 '15 at 9:33 community wiki
milad.moafi

 | 

simply code : use this code in onCreate()

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

|
  this answer
answered Jan 24 '16 at 6:19 community wiki
adnan9011

 | 

If you want to hide keyboard using Java code, then use this:

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

Or if you want to hide the keyboard always, then use this in your AndroidManifest:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />

|
  this answer
edited May 9 '16 at 18:59 community wiki
2 revs, 2 users 92%
user3102913      The java code solution worked for me in a fragment when I replaced fEmail with the view that opened the keyboard. It worked on Samsung Galaxy Tab S2 running Android 5.1.1, Nexus 5 running 6.0.1, and an XT1032 running 5.1 (This is using the support libraries.) –  Rock Lee May 24 '16 at 21:11

 | 

Simple and Easy to use method, just call hideKeyboardFrom(YourActivity.this); to hide keyboard

/**
 * This method is used to hide keyboard
 * @param activity
 */
public static void hideKeyboardFrom(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

|
  this answer
answered Feb 21 at 6:52 community wiki
Naveed Ahmad

 | 

Tried all here in desperation, combining all methods, and of course the keyboard will not close in Android 4.0.3 (it did work in Honeicomb AFAIR).

Then suddenly I found an apparently winning combination:

textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);

combined with your usual recipes

blahblaj.hideSoftInputFromWindow ...

hope this stops somebody from committing suicide .. I was close to it. Of course, I have no idea why it works.


|
  this answer
answered May 20 '13 at 15:52 community wiki
rupps

 | 

Depite all those answers, just to be simple enough, I have written a common method to do this :

/**
 * hide soft keyboard in a activity
 * @param activity
 */
public static void hideKeyboard (Activity activity){
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    if (activity.getCurrentFocus() != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
}

|
  this answer
answered Oct 31 '14 at 2:33 community wiki
Geng Jiawen

 | 

An alternative using SearchView would be to use this code:

searchView = (SearchView) searchItem.getActionView();    
searchView.setOnQueryTextListener(new OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        InputMethodManager imm = (InputMethodManager)
        getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchView.getApplicationWindowToken(), 0);
    }
}

This is a SearchView search box in the ActionBar that when the text from the query is submitted (the user presses either Enter key or a search button/icon), then the InputMethodManager code gets activated and makes your soft keyboard go down. This code was put in my onCreateOptionsMenu(). searchItem is from MenuItem which is part of the default code for the onCreateOptionsmenu(). Thanks to @mckoss for a good chunk of this code!


|
  this answer
edited Apr 24 '15 at 21:13 community wiki
2 revs, 2 users 79%
Noni A.

 | 

simple method guys: try this...

private void closeKeyboard(boolean b) {

        View view = this.getCurrentFocus();

        if(b) {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
        else {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }

|
  this answer
answered Mar 23 '16 at 7:04 community wiki
Joolah

 | 
public static void closeInput(final View caller) {  
    caller.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }, 100);
}

This method generally works, but there is one condition: you can't have android:windowSoftInputMode="any_of_these" set


|
  this answer
answered Jan 18 '14 at 18:54 community wiki
Jacek Kwiecień

 | 
private void hideSoftKeyboard() {
    View view = getView();
    if (view != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

|
  this answer
answered Sep 25 '14 at 14:24 community wiki
Lunatikul

 | 

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;

        }
    });

|
  this answer
answered Mar 29 '15 at 10:24 community wiki
user198829

 | 
/** 
 *
 *   Hide I Said!!!
 *
 */
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
    View currentFocus = activity.getCurrentFocus();
    if (currentFocus == null) {
        currentFocus = activity.getWindow().getDecorView();
        if (currentFocus != null) {
            return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
        }
    }
    return false;
}

public static boolean hideSoftKeyboard(@NonNull Context context) {
   if(Activity.class.isAssignableFrom(context.getClass())){
       return hideSoftKeyboard((Activity)context);
   }
   return false;
}

public static InputMethodManager getSoftInput(@NonNull Context context) {
    return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}

|
  this answer
answered Feb 9 '16 at 21:18 community wiki
ceph3us

 | 

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();
}

|
  this answer
answered Oct 6 '16 at 12:34 community wiki
Heena Arora

 | 
use Text watcher instead of EditText.and after you finished entering the input 

you can use

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

|
  this answer
answered Dec 7 '16 at 10:14 community wiki
koteswara D K

 | 

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

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

and it will work.


|
  this answer
answered Jan 16 at 4:39 community wiki
Mansuu....

 |  -1

This works for me :

 @Override
 public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);

if (v instanceof EditText) {
    View w = getCurrentFocus();
    int scrcoords[] = new int[2];
    w.getLocationOnScreen(scrcoords);
    float x = event.getRawX() + w.getLeft() - scrcoords[0];
    float y = event.getRawY() + w.getTop() - scrcoords[1];

    Log.d("Activity",
            "Touch event " + event.getRawX() + "," + event.getRawY()
                    + " " + x + "," + y + " rect " + w.getLeft() + ","
                    + w.getTop() + "," + w.getRight() + ","
                    + w.getBottom() + " coords " + scrcoords[0] + ","
                    + scrcoords[1]);
    if (event.getAction() == MotionEvent.ACTION_UP
            && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
                    .getBottom())) {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                .getWindowToken(), 0);
    }
}
return ret;
}

|
  this answer
edited Jul 27 '16 at 14:45 community wiki
2 revs, 2 users 98%
Siddharth_Vyas

 |  prev 1 2

protected by Jeff Atwood♦ Jul 12 '10 at 23:51

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged android android-softkeyboard android-keypad android-input-method soft-keyboard or ask your own question.

Recommend:How to hide Android Soft Keyboard

I have two EditText Views and a Button in Linearlayout. After Completion of writing in the edittext, I want to hide the Android Virtual keyboard, How can I do that android android-edittext android-softkeyboard android-virtual-keyboard shar

oriUlr:http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard?page=2&tab=votes

------splitte line----------------------------