【问题标题】:Hide Keyboard when select item from spinner in DialogFragment从 DialogFragment 中的微调器中选择项目时隐藏键盘
【发布时间】:2016-05-31 14:25:44
【问题描述】:
在从Spinner 中选择一个项目后,我试图隐藏键盘,但代码不起作用并且没有任何反应。但另一方面,相同的代码在正常片段中工作。
隐藏键盘的方法如下:
public static void hideKeypad(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
【问题讨论】:
标签:
android
android-softkeyboard
android-dialogfragment
dialogfragment
【解决方案1】:
您需要指定Fragment 的rootView,因为在您的方法中看到的是getCurrentFocus() == null,所以它永远不会转到其余代码。
这是正确的代码:
public static void hideKeypad(Activity activity, View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
创建一个类变量View 并将其与onCreateView() 中Fragment 的rootView 相等,并在此Fragment 中的任何位置使用此方法。
【解决方案2】:
这在片段中对我有用
public void removePhoneKeypad() {
if(getActivity().getCurrentFocus()!=null &&getActivity().getCurrentFocus().getWindowToken() != null) {
System.out.println("getCurrentFocus() in frag");
InputMethodManager inputManager = (InputMethodManager) rootView
.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
IBinder binder = getActivity().getCurrentFocus().getWindowToken();
inputManager.hideSoftInputFromWindow(binder,
InputMethodManager.HIDE_NOT_ALWAYS);
}
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}