输入按钮时将键盘隐藏在片段内

时间:2018-12-06 17:55:13

标签: java android

我在一个片段中,当我单击Enter键(在键盘上)时,我想隐藏键盘。我已经尝试过了,但是不起作用

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:cursorVisible="false"
    />


  edittext.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)) {
                getActivity().getWindow().setSoftInputMode(
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

1 个答案:

答案 0 :(得分:2)

首先创建一个hideSoftKeyboard()空隙。

public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

然后将OnEditorActionListener设置为edittext并调用hideSoftKeyboard()

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN ))){
                hideSoftKeyboard();
                return true;
            }
            else{
                return false;
            }
        }
    });

最后,我们向edittext添加了一些XML属性。

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/edittext"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:imeOptions="actionDone"
    android:singleLine="true"
    android:lines="1"
    android:inputType="text"/>