我想在AlertDialog解雇后隐藏软键盘,但它仍然可见。这是我的代码:
alert = new AlertDialog.Builder(MyActivity.this);
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
在Manifest xml中
android:windowSoftInputMode="stateAlwaysHidden"
它会在关闭
Dialog
时自动隐藏软键盘
我遇到了同样的问题。通过这样做解决了它。它不需要任何参考:
imm.hideSoftInputFromWindow(getWindow().getDecorView()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
关闭警报对话框时遇到了类似的问题。这似乎对我有用。
在DialogFragment中
public static void closeKB(final View view)
{
caller.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 1);
}
@Override
public void onDismiss(DialogInterface dialog)
{
super.onDismiss(dialog);
View view = getActivity().getCurrentFocus();
if (view != null)
{
closeKB(view);
}
}
我用这个方法:
IBinder token = searchTextEntry.getWindowToken();
( ( InputMethodManager ) getSystemService( Context.INPUT_METHOD_SERVICE ) ).hideSoftInputFromWindow( token, 0 );
其中searchTextEntry
是我的EditText
参考的名称。
protected void hideKeyboard() {
final Activity activity = getActivity();
final View view = activity != null ? activity.getCurrentFocus() : null;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (view != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}, 1);
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
hideKeyboard();
}
我遇到了所有这些解决方案的问题,但是如果你正在使用Fragment,请在这个帖子中找到@ amal-dev-s-i:How to hide keyboard on dialog dismiss
我只是将它添加到我的片段中,并且在对话框上调用dismiss()后它可以工作:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
我有类似的运气将上面的内容(删除getActivity())添加到父活动的onResume()中,如果它在一个活动中。
所有这些使用InputMethodManager
的建议都有些模糊 - 究竟是什么意思,
他们至少对我不起作用。
是的,键盘消失但随后应用程序崩溃了!?
主要问题是当对话框消失时隐藏键盘同时发生。
为了避免它,dialog.dismiss()
应该在view.postDelayed()
之后调用imm.hideSoftInputFromWindow()
,在我的情况下我将延迟设置为150。
这有效!这将在对话框关闭后关闭键盘
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);