在Android上隐藏键盘崩溃的应用程序

时间:2013-02-13 19:20:42

标签: java android crash android-context android-input-method

当我尝试运行此行以隐藏键盘时(我得到InputMethodManager):

this.context = context;
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); //this line crashes the app

我应该怎么做才能修复它? (顺便说一下,我是从片段中运行它)

崩溃日志:

11-03 16:20:26.700: D/AndroidRuntime(2809): Shutting down VM
11-03 16:20:26.700: W/dalvikvm(2809): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-03 16:20:26.710: E/AndroidRuntime(2809): FATAL EXCEPTION: main
11-03 16:20:26.710: E/AndroidRuntime(2809): java.lang.NullPointerException
11-03 16:20:26.710: E/AndroidRuntime(2809):     at co.emuze.tabtest1.Tab1$1.onClick(Tab1.java:32)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.view.View.performClick(View.java:4084)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.view.View$PerformClick.run(View.java:16966)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Handler.handleCallback(Handler.java:615)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Looper.loop(Looper.java:137)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at java.lang.reflect.Method.invoke(Method.java:511)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at dalvik.system.NativeStart.main(Native Method)

完全点击方式:

public void onClick(View v) {
                text1.setText(editText1.getText().toString());
                InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
            }

2 个答案:

答案 0 :(得分:1)

看起来上下文为空 - 您显示行this.context = context,如果右侧context不是该方法的本地变量,则您什么都不做。我认为您可能正在寻找的是context = getApplicationContext()

答案 1 :(得分:1)

不要忘记使用try catch博客,因为万一你的键盘没有打开,如果你使用键盘隐藏代码应用程序崩溃

用户在片段

中的代码下方
 try {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            // TODO: handle exception
       }