如果当前关注了edittext并且用户在DialogFragment外部单击;我希望屏幕键盘消失。当DialogFragment以这种方式被解雇时,我可以让它工作:
InputMethodManager imm;
public View onCreateView(LayoutInflater inflator, ViewGroup container,
Bundle savedInstanceState) {
imm = (InputMethodManager)getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
...}
@Override
public void dismiss(){
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
super.dismiss();
}
但是,如果我尝试通过触摸对话片段之外取消它时同样的事情,它将无效。我试图通过覆盖onCancel来做到这一点:
@Override
public void onCancel(DialogInterface dialog){
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
super.onCancel(dialog);
}
当外部触摸事件发生时调用该函数,但不删除键盘。
答案 0 :(得分:4)
我能够通过对对话框进行子类化并在执行对话框上的取消代码之前隐藏键盘来解决同样的问题。
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(), getTheme()) {
@Override public void cancel() {
if (getActivity() != null && getView() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
super.cancel();
}
};
return dialog;
}
我尝试了许多替代方法,包括使用DialogFragment的onCancel和onDimiss监听器无济于事。我认为问题是在同步处理解除/取消时异步调用侦听器;所以当你的监听器被调用来隐藏键盘时,窗口标记就不再存在了。
答案 1 :(得分:2)
这就是我为了最终工作而做的...我不需要将键盘用于键盘...但是当用户选择对话框外的东西时,使用currentfocus来获取windowtoken以移除键盘...
@Override
public void onStop() {
// make sure the keyboard goes away when the user selects something outside the view (cancelled outside)
if( Utilities.isValidActivity(this.getActivity())) {
InputMethodManager imm = (InputMethodManager)this.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// not the search view but the current focus at this point
imm.hideSoftInputFromWindow(this.getActivity().getCurrentFocus().getWindowToken(), 0);
}
super.onStop();
}
答案 2 :(得分:1)
我有同样的问题并通过在我产生DialogFragment的活动中将它放在AndroidManifest中来解决它:
android:windowSoftInputMode="stateHidden"
答案 3 :(得分:0)
尝试添加onDismissListener
这样的内容。
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
dismiss();
}
});