How to clear focus and remove keyboard on Android?

后端 未结 6 2058
情歌与酒
情歌与酒 2021-02-01 18:41

I have a EditText control. If I tap it the softkeyboard will popup however when I press \"enter/ok/return\" then the EditText control it still has focus and the keyboard up.

6条回答
  •  一生所求
    2021-02-01 19:34

    A Kotlin solution that works for me, removes all active focus and close the soft keyboard. Set android:focusableInTouchMode="true" on your parent layout. In my case I have a ScrollView as well. I am setting view.clearFocus() in its touch event listener. This will clear all the focus on any touched textview. Then I proceed to close the soft keyboard on screen.

    
    
    
        
    
    
            
    
            
    

    Then in your class

    scroll_view_container.setOnTouchListener { v, event ->
            view.clearFocus()
            hideSoftKeyboard()
            true
        }
    
    private fun hideSoftKeyboard() {
        val windowToken = view?.rootView?.windowToken
        windowToken?.let{
            val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(it, 0)
        }
    }
    

提交回复
热议问题