如何在没有视图的情况下获取Activity的windowToken?

41

现在,我尝试在用户触摸键盘之外时隐藏软键盘:

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

我想把逻辑放在我的基础活动类中,所以有没有可能在没有View的情况下获取getWindowToken?


1
这是一个错别字吗?"getgetWindowToken()"? - MKJParekh
2
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - Pratik Butani
7个回答

50

我在编写一个活动中的OnPageChangeListener时遇到了完全相同的问题。您可以使用以下其中一种解决方案:

getWindow().getDecorView().getRootView().getWindowToken()   
或:
findViewById(android.R.id.content).getWind‌​owToken()

19

你可以使用以下方法:

getContentView().getWindowToken()

或者您可以参考SO Quest


11
根据Hanry的建议解决了:findViewById(android.R.id.content).getWindowToken()。(注:该代码片段用于获取当前窗口的令牌。) - David Guo
10
没有getContentView()方法。请改用findViewById(android.R.id.content).getWindowToken()。 - mhsmith

8
只需使用 getWindow().getDecorView().getWindowToken()

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

1
你可以直接从窗口的WindowManager.LayoutParams中获取令牌。
getWindow().getAttributes().token

从文档中,“这通常会为您填写。”。这很奇怪 :) - Vlad

1

在Kotlin中:

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

或者,如果你有一个视图:
imm.hideSoftInputFromWindow(view.windowToken, 0)

0
您可以尝试在清单文件的活动标记上使用此代码来隐藏键盘。
 android:windowSoftInputMode="stateHidden"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接