用于输入键的TextView的setOnKeyListener不起作用

时间:2015-06-11 14:17:59

标签: android keylistener

我在onCreate中有以下代码:

commentET = (EditText) findViewById(R.id.comment);
commentET.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
               case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    Log.i("UdazzT", "enter pressed");
                    return true;
                default:
                    break;
            }
        }
        return false;
    }
});

和布局:

<EditText android:hint="@string/comment"
    ...
    android:imeOptions="actionGo"/>

我还尝试过actionSend和actionSearch

3 个答案:

答案 0 :(得分:1)

我找到了解决方案:

    commentET = (EditText) findViewById(R.id.comment);
    commentET.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                perform action
                return true;
            }
            return false;
        }
    });

答案 1 :(得分:0)

android:imeOptions="actionGo"对应EditorInfo.IME_ACTION_GO

    commentET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(final TextView textView, final int keyCode, final KeyEvent keyEvent) {
            if (keyCode == EditorInfo.IME_ACTION_GO) {
                // ...
                return true;
            }
            return false;
        }

    });

我个人使用:

final Integer[] enterKeys = {
    EditorInfo.IME_ACTION_GO,
    KeyEvent.KEYCODE_DPAD_CENTER,
    KeyEvent.KEYCODE_ENTER
};
if (Arrays.asList(enterKeys).contains(keyCode)) {
    // ...
}

答案 2 :(得分:0)

我实际上使用这个静态帮助器方法来确定KeyEvent是否为Enter Action,因为某些设备制造商不喜欢遵循标准(例如,有时KeyEvent实际上可能为null,或者它可能是ACTION_DOWN):

public static boolean isSoftKeyboardFinishedAction(TextView view, int action, KeyEvent event){
    // Some devices return null event on editor actions for Enter Button
    return (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_GO || action == EditorInfo.IME_ACTION_SEND) && (event == null || event.getAction() == KeyEvent.ACTION_DOWN);
}

然后我只用以下方法实现:

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int action, KeyEvent event) {
            if (isSoftKeyboardFinishedAction(view, action, event)) {
                // Do something
                return true;
            }
            return false;
        }
    }); 

显然,使用Listcontains()时,shkschneider的回答更清晰,但您还需要考虑KeyEvent,否则回调会在某些情况下触发两次设备