Search code examples
androidandroid-softkeyboard

How to hide Soft Keyboard when activity starts


I have an Edittext with android:windowSoftInputMode="stateVisible" in Manifest. Now the keyboard will be shown when I start the activity. How to hide it? I cannot use android:windowSoftInputMode="stateHidden because when keyboard is visible then minimize the app and resume it the keyboard should be visible. I tried with

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

but it did not work.


Solution

  • If you don't want to use xml, make a Kotlin Extension to hide keyboard

    // In onResume, call this
    myView.hideKeyboard()
    
    fun View.hideKeyboard() {
        val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
    }
    

    Alternatives based on use case:

    fun Fragment.hideKeyboard() {
        view?.let { activity?.hideKeyboard(it) }
    }
    
    fun Activity.hideKeyboard() {
        // Calls Context.hideKeyboard
        hideKeyboard(currentFocus ?: View(this))
    }
    
    fun Context.hideKeyboard(view: View) {
        view.hideKeyboard()
    }
    

    How to show soft keyboard

    fun Context.showKeyboard() { // Or View.showKeyboard()
        val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
    }
    

    Simpler method when simultaneously requesting focus on an edittext

    myEdittext.focus()
    
    fun View.focus() {
        requestFocus()
        showKeyboard()
    }
    

    Bonus simplification:

    Remove requirement for ever using getSystemService: Splitties Library

    // Simplifies above solution to just
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)