当我试图运行此行以隐藏键盘时(我得到了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);
}
上下文似乎为null-显示行this.context = context
,如果右侧的context
不是该方法的局部变量,则什么也不做。我想您可能正在寻找的是context = getApplicationContext()
不要忘记使用try-catch博客,因为如果你的键盘没有打开,如果你使用按键板隐藏代码应用程序崩溃
碎片中代码下方的用户
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}