我的布局中有一个EditText和一个Button。

在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?


当前回答

如果这里的所有其他答案都不适合您,那么还有另一种手动控制键盘的方法。

创建一个用于管理EditText的某些财产的函数:

public void setEditTextFocus(boolean isFocused) {
    searchEditText.setCursorVisible(isFocused);
    searchEditText.setFocusable(isFocused);
    searchEditText.setFocusableInTouchMode(isFocused);

    if (isFocused) {
        searchEditText.requestFocus();
    }
}

然后,确保在EditText的焦点上打开/关闭键盘:

searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v == searchEditText) {
            if (hasFocus) {
                // Open keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED);
            } else {
                // Close keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
            }
        }
    }
});

现在,每当您想要打开键盘时,请手动调用:

setEditTextFocus(true);

对于结束通话:

setEditTextFocus(false);

其他回答

在Android中,要通过InputMethodManage隐藏Vkeyboard,您可以通过传递包含焦点视图的窗口的标记来隐藏SoftInputFromWindow。

View view = this.getCurrentFocus();
if (view != null) {  
InputMethodManager im = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

通过调用editText.clearFocus(),然后调用InputMethodManager.HIDE_IMPLICIT_ONLY甚至可以工作

public final class UtilsKeyboard {
/**
 * Sets the cursor at the end of this edit text and shows a keyboard
 */
public static void focusKeyboard(@NonNull EditText editText) {
    editText.requestFocus();
    editText.setSelection(editText.getText().length());
    showKeyboard(editText);
}

private static void showKeyboard(@NonNull View view) {
    final InputMethodManager manager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (manager != null) {
        manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

public static boolean hideKeyboard(@NonNull Window window) {
    View view = window.getCurrentFocus();
    return hideKeyboard(window, view);
}

private static boolean hideKeyboard(@NonNull Window window, @Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) window.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

public static boolean hideKeyboard(@Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

/**
 * This will hide the keyboard and unfocus any focused view.
 */
public static void unfocusKeyboard(@NonNull Window window) {
    // When showing the bottom menu, make sure the keyboard isn't and that no view has focus
    hideKeyboard(window);
    final View focused = window.getCurrentFocus();
    if (focused != null) focused.clearFocus();
}}

有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性

 android:imeOptions="actionDone" 

这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。

当您想手动隐藏键盘时,单击按钮:

/**
 * Hides the already popped up keyboard from the screen.
 *
 */
public void hideKeyboard() {
    try {
        // use application level context to avoid unnecessary leaks.
        InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        assert inputManager != null;
        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

当您想在屏幕上除编辑文本以外的任何地方隐藏键盘时在活动中重写此方法:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

只需在BaseActivity和BaseFragment中为整个应用程序创建通用方法

在onCreate()中初始化inputMethodManager

inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

使用此方法隐藏和显示键盘

public void hideKeyBoard(View view) {
     if (view != null) {
         inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
      }
 }

public void showKeyboard(View view, boolean isForceToShow) {
      if (isForceToShow)
         inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
      else if (view != null)
           inputMethodManager.showSoftInput(view, 0);
}