David Guo
David Guo

Reputation: 1759

how to get Activity's windowToken without view?

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?

Upvotes: 41

Views: 31481

Answers (7)

Shivam Jha
Shivam Jha

Reputation: 4522

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)

Upvotes: 1

tynn
tynn

Reputation: 39853

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

getWindow().getAttributes().token

Upvotes: 1

Bertram Gilfoyle
Bertram Gilfoyle

Reputation: 10235

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

Upvotes: 8

Akash Bisariya
Akash Bisariya

Reputation: 4754

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

 android:windowSoftInputMode="stateHidden"

Upvotes: 0

ceph3us
ceph3us

Reputation: 7474

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

Upvotes: 1

divonas
divonas

Reputation: 1022

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

Upvotes: 50

Hanry
Hanry

Reputation: 5531

Surely you can use:

getContentView().getWindowToken()

or you can refer to SO Quest

Upvotes: 19

Related Questions