关闭对话框时隐藏软键盘

10

我正在一个Activity中打开一个Dialog。当对话框打开时,我调用

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

问题是,我关闭对话框时,无论是按取消按钮还是在对话框外面点击,键盘都会切换到文本键盘,并且直到我点击硬件返回按钮才会消失。当对话框消失并且焦点返回到先前的窗口时,如何使键盘消失?


有任何解决方案吗? - tactoth
5个回答

10
AndroidManifest.xml 文件中,为显示 DialogActivity 设置以下属性:

android:windowSoftInputMode="stateAlwaysHidden"

注意!不是 stateHiddent,而是 stateAlwaysHidden。设置此属性将在 Dialog 关闭时自动隐藏软键盘。
希望这可以帮助你。

谢谢@Weiliang Chik,你节省了我的时间。 - Parmar Subhash
@ParmarSubhash,不是你的生命吗? - Faser

1
AlertDialog.Builder builder = new AlertDialog.Builder(EllipticalActivity.this);
builder.setTitle("title")
       .setMessage("message")
       .setCancelable(false)
       .setNegativeButton("Close", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               InputMethodManager inputManager = 
                   (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
               inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                                    InputMethodManager.HIDE_NOT_ALWAYS);
               dialog.cancel();
           }
        });
        AlertDialog alert = builder.create();
        alert.show();

看了你的代码,这只会在我点击一个按钮时关闭键盘。我希望它能因为更多的原因而关闭:点击按钮、点击外部或对话框完成任务。更有意义的是,只需检测对话框何时被解除,而不是列出所有可能的窗口解除方式。 - gatzkerob

1

我想这种活动方法对你可能会有所帮助。

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus)
        {
            Toast.makeText(MainActivity.this, "has focus", Toast.LENGTH_LONG).show();
                        // write code to remove keyboard
        }
    }

0

从 Activity 的 onCreateView() 方法中,您可以这样做:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

或者在 Manifest xml 中

android:windowSoftInputMode="stateAlwaysHidden"

在对话框关闭时,它将自动隐藏软键盘


0
在我的情况下,解决方案是在对话框关闭时隐藏键盘。
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接