How to hide soft keyboard on android after clicking outside EditText?

前端 未结 30 2149
醉话见心
醉话见心 2020-11-22 11:46

Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hi         


        
30条回答
  •  深忆病人
    2020-11-22 12:14

    A more Kotlin & Material Design way using TextInputEditText (this approach is also compatible with EditTextView)...

    1.Make the parent view(content view of your activity/fragment) clickable and focusable by adding the following attributes

    android:focusable="true"
    android:focusableInTouchMode="true"
    android:clickable="true"
    

    2.Create an extension for all View (inside a ViewExtension.kt file for example) :

    fun View.hideKeyboard(){
        val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(this.windowToken, 0)
    }
    

    3.Create a BaseTextInputEditText that inherit of TextInputEditText. Implement the method onFocusChanged to hide keyboard when the view is not focused :

    class BaseTextInputEditText(context: Context?, attrs: AttributeSet?) : TextInputEditText(context, attrs){
        override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect)
            if (!focused) this.hideKeyboard()
        }
    }
    

    4.Just call your brand new custom view in your XML :

    
    
            
    
         
    

    That's all. No need to modify your controllers (fragment or activity) to handle this repetitive case.

提交回复
热议问题