38

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,669
  • 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

48

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
  • 902
  • 1
  • 9
  • 11
19

Surely you can use:

getContentView().getWindowToken()

or you can refer to SO Quest

Community
  • 1
  • 1
Hanry
  • 5,441
  • 2
  • 40
  • 52
7

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

Bertram Gilfoyle
  • 9,188
  • 6
  • 39
  • 65
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,115
  • 3
  • 35
  • 41
1

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

getWindow().getAttributes().token
tynn
  • 36,131
  • 8
  • 97
  • 135
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
  • 2,153
  • 1
  • 17
  • 29
0

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

 android:windowSoftInputMode="stateHidden"
Akash Bisariya
  • 2,777
  • 1
  • 28
  • 40