Android dismiss keyboard

后端 未结 9 495
面向向阳花
面向向阳花 2021-01-29 23:51

How do I dismiss the keyboard when a button is pressed?

相关标签:
9条回答
  • 2021-01-30 00:27

    The first solution with InputMethodManager worked like a champ for me, the getWindow().setSoftInputMode method did not on android 4.0.3 HTC Amaze.

    @Ethan Allen, I did not need to make the edit text final. Maybe you are using an EditText inner class that you declared the containing method? You could make the EditText a class variable of the Activity. Or just declare a new EditText inside the inner class / method and use findViewById() again. Also, I didn't find that I needed to know which EditText in the form had focus. I could just pick one arbitrarily and use it. Like so:

        EditText myEditText= (EditText) findViewById(R.id.anyEditTextInForm);  
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
    
    0 讨论(0)
  • The solution above doesn't work for all device and moreover it's using EditText as a parameter. This is my solution, just call this simple method:

    private void hideSoftKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    
        if(imm.isAcceptingText()) { // verify if the soft keyboard is open                      
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
    
    0 讨论(0)
  • 2021-01-30 00:35

    Here's a Kotlin solution (mixing the various answers in thread)

    Create an extension function (perhaps in a common ViewHelpers class)

    fun Activity.dismissKeyboard() {
        val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
        if( inputMethodManager.isAcceptingText )
            inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
    }
    

    Then simply consume using:

    // from activity
    this.dismissKeyboard()
    
    // from fragment
    activity.dismissKeyboard()
    
    0 讨论(0)
提交回复
热议问题