在 Fragment 中隐藏键盘
Hiding Keypad within Fragment
我在尝试将键盘隐藏在 activity:
的片段内时遇到这些错误
Error: Cannot resolve getSystemService
Cannot resolve Context
Cannot resolve getCurrentFocus()
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
在片段中你应该使用 getActivity(),
InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
老实说,我从来没有从片段中关闭键盘的运气。我不明白它背后的工程原理,但这是有效的。
MainActivity-
public void closeKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
片段
private void closeKeyboard() {
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.closeKeyboard();
}
然后只需在 Fragment 中的任意位置调用您的方法 closeKeyboard()
我在尝试将键盘隐藏在 activity:
的片段内时遇到这些错误Error: Cannot resolve getSystemService
Cannot resolve Context
Cannot resolve getCurrentFocus()
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
在片段中你应该使用 getActivity(),
InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
老实说,我从来没有从片段中关闭键盘的运气。我不明白它背后的工程原理,但这是有效的。
MainActivity-
public void closeKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
片段
private void closeKeyboard() {
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.closeKeyboard();
}
然后只需在 Fragment 中的任意位置调用您的方法 closeKeyboard()