我正在尝试使用ButterKnife的OnEditorAction接口来编辑EditText的“ENTER”事件
@OnEditorAction(R.id.et_good)
boolean onEditorAction(EditText editText, int actionId, KeyEvent keyEvent) {
if (keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
updateArticle(editText.getText().toString().toUpperCase().trim());
}
return keyEvent.getAction() == KeyEvent.KEYCODE_ENTER;
}
但是我一直在那里获得EXCEPTION
com.xxx.xxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxx.xxx, PID: 6391
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.KeyEvent.getAction()' on a null object reference
at com.xxx.xxx.MainActivity.onEditorAction(MainActivity.java:68)
at com.xxx.xxx.MainActivity_ViewBinding$1.onEditorAction(MainActivity_ViewBinding.java:47)
at android.widget.TextView.onEditorAction(TextView.java:5911)
at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:360)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
布局xml文件也供您参考。
<EditText
android:id="@+id/et_good"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:paddingStart="10dp"
android:singleLine="true"
android:imeOptions="actionDone"
app:layout_constraintEnd_toStartOf="@+id/xxx"
app:layout_constraintStart_toEndOf="@+id/xxx"
app:layout_constraintTop_toBottomOf="@+id/xxx" />
请建议我错过了什么。
试试这个,因为你的xml中定义了android:imeOptions="actionDone"
,这应该可行。
@OnEditorAction(R.id.et_good)
boolean onEditorAction(EditText editText, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
updateArticle(editText.getText().toString().toUpperCase().trim());
}
return actionId == EditorInfo.IME_ACTION_DONE;
}
根据API参考文档here,如果事件不是Enter键事件,则keyEvent对象将为null。它可能是EditText上的任何其他事件(例如:在您的情况下为焦点事件。)