41

Now, I try to hide the softkeyboard when user touch outside the keyboard:

((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(editView.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);

I want put the logic in my base activity class, so if it is possible to getWindowToken without View?

David Guo
  • 1,749
  • 3
  • 20
  • 30
  • 1
    is this a typos "getgetWindowToken()"? – MKJParekh Oct 17 '11 at 05:09
  • 2
    possible duplicate of [how to hide soft keyboard on android after clicking outside EditText?](http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext) – Reno Oct 17 '11 at 05:11
  • 2
    `InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);` `inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);` – Pratik Butani Sep 23 '13 at 07:19

7 Answers7

50

I faced exactly the same problem, while writing OnPageChangeListener within an Activity. You can use one of these solutions. Either:

getWindow().getDecorView().getRootView().getWindowToken()   

or:

findViewById(android.R.id.content).getWind‌​owToken()
divonas
  • 992
  • 1
  • 10
  • 11
19

Surely you can use:

getContentView().getWindowToken()

or you can refer to SO Quest

Community
  • 1
  • 1
Hanry
  • 5,481
  • 2
  • 40
  • 53
8

Simply use getWindow().getDecorView().getWindowToken()

Bertram Gilfoyle
  • 9,899
  • 6
  • 42
  • 67
1
public static final String M_TOKEN = "mToken";

@Nullable
protected IBinder getToken(Activity activity) {
    try {
        Field mTokenField = Activity.class.getDeclaredField(M_TOKEN);
        mTokenField.setAccessible(true);
        IBinder mToken = (IBinder) mTokenField.get(activity);
        return mToken;
    } catch (NoSuchFieldException e) {
        // handle 
    } catch (IllegalAccessException e) {
       // handle
    }
    return null;
}
ceph3us
  • 7,326
  • 3
  • 36
  • 43
1

You could just get the token from the WindowManager.LayoutParams of the window directly

getWindow().getAttributes().token
tynn
  • 38,113
  • 8
  • 108
  • 143
1

In kotlin:

val imm  = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(window.attributes.token, 0)

Or, If you have a view:

imm.hideSoftInputFromWindow(view.windowToken, 0)
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
0

You can try this on your manifest file activity tag to hide keyboard.

 android:windowSoftInputMode="stateHidden"
Akash Bisariya
  • 3,855
  • 2
  • 30
  • 42