对话框打开时如何隐藏键盘

时间:2019-08-23 08:17:57

标签: android kotlin dialog keyboard

在其他情况下打开对话框时,HideKeyboard方法不起作用。

我在堆栈上尝试了所有流行的hideKeyboard方法,但它们都不起作用。

fun hideKeyboard(activity: Activity) {
    if(activity == null) return
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm?.hideSoftInputFromWindow(activity.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

我没有收到任何错误,但键盘无法关闭。

4 个答案:

答案 0 :(得分:2)

  1. 首先,您将调用隐藏键盘方法。我在下面给出了隐藏键盘方法的显示类型。如果您想使用喜欢的方法。
    public void hideKeyboard(View view, Context context) {
            try {
                if (view != null) {
                    InputMethodManager imm = (InputMethodManager) 
                    context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            } catch (Exception Ex) {
            }
        }
    
        public static void hideKeyboard(Activity activity) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            View view = activity.getCurrentFocus();
            if (view == null) {
                view = new View(activity);
            }
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
  1. 然后您将调用 Dialog。

结论首先你调用hide方法,然后调用Dialog。所以当调用hide方法时隐藏键盘,然后在调用对话框后再次调用Dialog然后打开。

答案 1 :(得分:1)

HideKeyboard function Android Code 

public void hideKeyboard(视图视图,上下文上下文) {

       try {

        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception Ex) {
    }
}

答案 2 :(得分:0)

尝试

public static void hideKeyboardFrom(Context context, View view) 
{ 
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
}

科特林(Kotlin)

fun hideKeyboard(context : Context, view : View) 
{ 
    val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager 
    imm.hideSoftInputFromWindow(view.windowToken, 0) 
}

答案 3 :(得分:0)

如果您使用的是AlertDialog,则可以执行以下操作。您可以从alertDialog对象获取getWindow()

alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
相关问题