Android中使用黄油刀的OnEditorAction中的空对象引用

时间:2019-03-21 03:13:24

标签: android android-edittext androidx butterknife

我试图将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;
}

但是我不断在哪里获得惊喜

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" />

请告诉我我错过了什么。

2 个答案:

答案 0 :(得分:1)

尝试一下,由于您在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;
}

答案 1 :(得分:0)

根据API参考文档here,如果事件不是NOT Enter键事件,则keyEvent对象将为null。可能是EditText上的任何其他事件(例如,您所关注的焦点事件。)