Close/hide the Android Soft Keyboard with Kotlin

I'm trying to write a simple Android app in Kotlin. I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard.

There is a popular question Close/hide the Android Soft Keyboard about doing it in Java, but as far as I understand, there should be an alternative version for Kotlin. How should I do it?


I think we can improve Viktor's answer a little. Based on it's always attached to a view, there will be context, if there is context then there is InputMethodManager

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

In this case the context automatically means the context of the view. What do you think?


Peter's solution solves neatly the problem by extending functionality of View class. Alternative approach could be to extend functionality of Activity class and thus bind operation of hiding keyboard with View's container rather than View itself.

fun Activity.hideKeyboard() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
}

You can use Anko to make life easier, so the line would be:

inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)

or maybe better to create extension function:

fun View.hideKeyboard(inputMethodManager: InputMethodManager) {
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

and call it like this:

view?.hideKeyboard(activity.inputMethodManager)
链接地址: http://www.djcxy.com/p/2726.html

上一篇: SQL注入绕过MySQL

下一篇: 用Kotlin关闭/隐藏Android软键盘