java - 使用InputMethodManager时给出空指针 imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

标签 java android

嗨,我正在尝试输入这段代码来隐藏 Android 上的软键盘,但它返回一个空指针。

代码:

public void testSetTestEnvironment (){
    solo.clickInList(4);
    solo.clickOnMenuItem(ConfigVariables.CATALOGSERVER);
    assertTrue(solo.searchText(ConfigVariables.CATALOGSERVERURL));


    //Enter KeyCode
     solo.clickInList(5);

    View myEditText = solo.getViews().get(0);
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(myEditText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);

    solo.enterText(solo.getEditText(0), "");
    solo.enterText(0, ConfigVariables.KEYCODE);

    assertTrue(popupClickButtonHandler("Enter KeyCode", "OK"));

日志显示:

java.lang.NullPointerException

谢谢。

最佳答案

也许有点太晚了,但我希望这对某人有帮助。 您的代码很容易出现错误,因为它依赖于聚焦 View 来获取窗口 token 。

尝试使用:

InputMethodManager im = (InputMethodManager) this.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

这段代码对我来说工作正常。

取自 this answer通过 venator85

关于java - 使用InputMethodManager时给出空指针 imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942152/

相关文章:

java - gwt 应用程序突然停止运行

java - 从 Java/Android 中的 URL 获取域名

java - RejectedExecutionHandler - CallerRunsPolicy 与 AbortPolicy

Android 推送通知服务未在 Lollipop 上启动

android - 当 ViewGroup 的 sibling 消失时,我如何才能使 ViewGroup 的 child match_parent ?

用于解析 Latex 或 MathML 字符串的 Java 或 scala 库

java - 当 Inputstream 中没有数据时跳过在 FileOutputStream 中创建文件

android - Android Webview-HTTP错误504网关超时

java - 将 JSON 映射到 Java 中的数组/对象 - Android

java - 过渡和 fragment