关闭按钮上的键盘单击该关闭片段

Dismiss Keyboard on button click that close fragment

如何在单击按钮时关闭键盘?我有一个片段,其中有一个 EditText 和两个按钮。一个提交 EditText 内容,另一个简单地关闭片段。现在,当片段消失时,键盘仍然存在。但是,按下后退按钮会关闭键盘或单击 "done" 也会将其关闭。但我需要的是当片段关闭时键盘消失。

我尝试过类似问题的解决方案 here,here or here 但 none 似乎有效。他们中的大多数人抛出 NullPointerException。所有都是为了活动而不是片段。调用键盘的代码有效:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

但是我必须添加 getActivity() 才能使其工作。

任何帮助将不胜感激。

使用这个方法

public void hideKeyboard() {
    // Check if no view has focus:
    View view = getActivity().getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

试试下面的方法

public static void hideKeyboard(Context mContext) {

    try {

        View view = ((Activity) mContext).getWindow().getCurrentFocus();

        if (view != null && view.getWindowToken() != null) {

            IBinder binder = view.getWindowToken();

            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(binder, 0);

        }

    } catch (NullPointerException e) {

        e.printStackTrace();

    }

}

在此方法中,您必须传递上下文参数。希望对您有所帮助。

对于片段使用以下函数

  public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

点击按钮时调用

  btn_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hideKeyboard(getActivity());
        }
    });

从以前的答案和 Kotlin 中发展而来,使用调用视图获取 window 令牌。

button.setOnClickListener() { view ->
        hideKeyboard(view)
}

private fun hideKeyboard(view: View) {
    val inputMethodManager = view.context.getSystemService(Activity.INPUT_METHOD_SERVICE)
            as InputMethodManager

    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

经过深思熟虑,与其将此调用添加到每个按钮,不如在失去焦点时清除键盘更有意义。

input.setOnFocusChangeListener { view, hasFocus ->
        if(!hasFocus) {
            hideKeyboard(view)
        }
    }