Android如何在按下Enter键时隐藏键盘(在EditText中)?

27

当我的用户在虚拟安卓"用户验证输入!"键盘上按下Enter时,我的键盘保持可见状态!(为什么?)

这是我的Java代码...

private void initTextField() {
    entryUser = (EditText) findViewById(R.id.studentEntrySalary);
    entryUser.setOnKeyListener(new 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:
                        userValidateEntry();
                        return true;
                }
            }

          return true;
        }
    });
}

private void userValidateEntry() {
    System.out.println("user validate entry!");
}

这是我的视图(View)

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <EditText android:id="@+id/studentEntrySalary" android:text="Foo" android:layout_width="wrap_content" android:layout_height="wrap_content" />
 </LinearLayout>
也许我的虚拟设备出了些问题?
5个回答

68
这应该就可以了:
yourEditTextHere.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                // NOTE: In the author's example, he uses an identifier
                // called searchBar. If setting this code on your EditText
                // then use v.getWindowToken() as a reference to your 
                // EditText is passed into this callback as a TextView

                in.hideSoftInputFromWindow(searchBar
                        .getApplicationWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
               userValidateEntry();
               // Must return true here to consume event
               return true;

            }
            return false;
        }
    });

2
你是个天才!谢谢。 (将searchBar改为yourEditTextHere) - Martin Magakian
1
当我把代码改成以下内容时:if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_D)),代码似乎无法运行。这样,在按下D键后,软输入表单就不会隐藏。 - Samir
5
如果其他人看到Samir的评论,那是因为这段代码设置了OnEditorActionListener,只有在按下像回车之类的键时才会被调用,并不包括普通的字符键。 - Nora Powers
如果我真的需要在“普通”字符按下时隐藏键盘?有什么想法吗? - tba

18

保留singleLine="true",并在EditText中添加imeOptions="actionDone"。 然后在OnEditorActionListener中检查actionId == EditorInfo.IME_ACTION_DONE,像这样(但将其更改为您自己的实现):

if (actionId == EditorInfo.IME_ACTION_DONE) {

                if ((username.getText().toString().length() > 0)
                        && (password.getText().toString().length() > 0)) {
                    // Perform action on key press
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(username.getWindowToken(),
                            0);
                    doLogin();
                }
            }

6
对于我的情况,只需要 imeOptions="actionDone" 就足够了,不需要编写代码。 - 1615903

5

2
仍然存在与android:singleLine="true"相关的问题。 - Martin Magakian
这对我来说是可行的,使用Android 4(平板电脑4.0.3,构建目标4.2),如果它与Android版本有关(我没有在其他版本上尝试过)。 - Mick

2
只需在您的编辑文本中添加此行。
android:imeOptions="actionDone"'

你可以指定下一个编辑文本的ID,在键盘完成按钮点击时移动到该编辑文本。

1
我正在创建一个自定义组件,它继承了AutoCompleteTextView,就像下面的示例一样:
public class PortugueseCompleteTextView extends AutoCompleteTextView {
...
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (event != null &&  (event.getKeyCode() == KeyEvent.KEYCODE_BACK)) {
        InputMethodManager inputManager =
                (InputMethodManager) getContext().
                        getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(
                this.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }
    return super.onKeyPreIme(keyCode, event);
}

我正在AlertDialog.Builder中使用此代码,但也可以在Activity中使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接