Home > Software design >  I want to hide the keyboard
I want to hide the keyboard

Time:03-30

i want to hide the keyboard but i want to write it in a class. To use it for all activities. ı need a edit text delete focus code

class Extensions(){
fun hideSoftKeyboard(view: View) {
    val imm =getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

}

problem description

No value passed for parameter 'serviceClass'

Type mismatch: inferred type is String but Context was expected

new code: but I couldn't do the outer click event

fun Activity.hideKeyboard() {
    val view = currentFocus
    if (view != null) {
        view.clearFocus()
        val inputMethodManager =
            getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

        inputMethodManager.hideSoftInputFromWindow(
            view.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}

CodePudding user response:

You can make an Extenstion function on the edit text that would do that for you

fun EditText.hideKeyboard() {
    clearFocus()
    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(getWindowToken(), 0)
}

I haven't tested it out yet, please test that one out and tell me if it does work.

CodePudding user response:

Extensions.kt

fun Activity.hideKeyboard(event: MotionEvent) {
    if (event.action == MotionEvent.ACTION_DOWN){
        val view = currentFocus
        if (view != null) {
            view.clearFocus()
            val outRect = Rect()
            view.getGlobalVisibleRect(outRect)
            if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                val inputMethodManager =
                    getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

                inputMethodManager.hideSoftInputFromWindow(
                    view.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        }
    }
}

YouActivity

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        hideKeyboard(event)
        return super.dispatchTouchEvent(event)
    }

CodePudding user response:

if you are using Jetpack Compose;

@Composable
fun MainScreenView(){

    val keyboardController = LocalSoftwareKeyboardController.current
    keyboardController.hide()

  • Related