我的View上有一个EditText,我想设置一个onKeyListener。
这是我的代码:
final EditText edittext = (EditText) findViewById(R.id.editText1);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edittext.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
});
}
问题是我遇到了这个问题,这是logcat的一个错误部分:
W/dalvikvm(3703): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime(3703): FATAL EXCEPTION: main
E/AndroidRuntime(3703): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{milos.mdpi/milos.mdpi.MDPIActivity}: java.lang.NullPointerException
E/AndroidRuntime(3703): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
E/AndroidRuntime(3703): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime(3703): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime(3703): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime(3703): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(3703): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(3703): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(3703): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3703): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(3703): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(3703): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(3703): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(3703): Caused by: java.lang.NullPointerException
E/AndroidRuntime(3703): at android.app.Activity.findViewById(Activity.java:1647)
E/AndroidRuntime(3703): at milos.mdpi.MDPIActivity.<init>(MDPIActivity.java:22)
E/AndroidRuntime(3703): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(3703): at java.lang.Class.newInstance(Class.java:1409)
E/AndroidRuntime(3703): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
E/AndroidRuntime(3703): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
E/AndroidRuntime(3703): ... 11 more
答案 0 :(得分:7)
private EditText edittext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<yourlayout>.xml);
edittext = (EditText) findViewById(R.id.editText1);
edittext.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
});
}
如果问题仍然存在,并且您仍然获得NPE,您的EditText可能在您的布局xml中有其他ID。
答案 1 :(得分:2)
你需要写
设置ContentView setContentView(R.layout.main);
EditText edittext = (EditText) findViewById(R.id.editText1);
<{1>}中的而不是onCreate()
。
答案 2 :(得分:1)
的setContentView(R.layout.main);缺少