esQ*_*mo_ 7 android android-softkeyboard android-edittext android-fragments
如何在按钮单击时关闭键盘?我有一个片段,它有一个EditText和两个按钮.一个提交EditText内容,另一个只是关闭片段.现在当片段消失时,键盘会停留.但是,按后退按钮会关闭键盘或单击"完成"也会关闭它.但我需要的是当片段关闭时键盘消失.
我在这里,这里或这里尝试过类似问题的解决方案,但似乎都没有效果.大多数人扔了一个NullPointerException.一切都是为了活动而不是碎片.调用键盘的代码有效:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Run Code Online (Sandbox Code Playgroud)
但是我必须添加getActivity()才能使它工作.
任何帮助将不胜感激.
sre*_*v s 14
使用此方法
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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
对于片段使用以下函数
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);
}
Run Code Online (Sandbox Code Playgroud)
单击按钮时调用它
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideKeyboard(getActivity());
}
});
Run Code Online (Sandbox Code Playgroud)