Question: I would like to close the soft keyboard from inside a fragment.
I am finding a lot of answers but they are all in Java. Usually I am able to transition it to Kotlin quite easily but I am having a hard time with this one.

The closest I got was this:

```
fun closeKeyboard() {
    val activity = activity as FeedActivity

    val view = activity.currentFocus
    if (view != null) {
        val imm = ContextCompat.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        imm!!.hideSoftInputFromWindow(view!!.getWindowToken(), 0)
    }
}

```

But I am having trouble with this part `getSystemService(Context.INPUT_METHOD_SERVICE)`

Answer: 
All is right except `ContextCompat.getSystemService`. Use `Activity` instance instead `ContextCompat`.

```
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view!!.getWindowToken(), 0)

```
I came here looking for an answer to a similar question in a context where I didn't have direct access to an `Activity` instance.

Although the accepted answer works, you can still use `ContextCompat` if you pass the class of the service you are requesting, with the benefit of having the cast done for you, like this:

```
val imm = ContextCompat.getSystemService(view.context, InputMethodManager::class.java)
imm?.hideSoftInputFromWindow(view.windowToken, 0)

```