Hide to show and hide keyboard in DialogFragment

后端 未结 8 2188
花落未央
花落未央 2021-02-08 03:57

In my dialog fragment, I am able to show the keyboard using

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);
         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 04:34

    I had extension for fragment, but didn't work with dialog fragment. This extension works for both (not tested much tho)

    /**
     * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
     *
     * @param useReflection - whether to use reflection in case of no window token or not
     */
    fun Fragment.hideKeyboard(context: Context = App.instance, useReflection: Boolean = true) {
        val windowToken = view?.rootView?.windowToken
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        windowToken?.let {
            imm.hideSoftInputFromWindow(windowToken, 0)
        } ?: run {
            if (useReflection) {
                try {
                    if (getKeyboardHeight(imm) > 0) {
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                    }
                } catch (exception: Exception) {
                    Timber.e(exception)
                }
            }
        }
    }
    
    fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int
    

    Edit: toggle opened keyboard if it was closed before, I use reflection to get keyboard's height, which is not best solution, but works

提交回复
热议问题