Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the soft keyboard from a fragment using Kotlin?

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)

like image 473
Tsabary Avatar asked Apr 03 '19 22:04

Tsabary


1 Answers

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)
like image 86
Andrew Churilo Avatar answered Nov 01 '22 08:11

Andrew Churilo