oligazar
6/22/2017 - 6:45 AM

Keyboard helpers

Keyboard helpers


// show keyboard
fun Activity.showSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val isShowing = inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        if (!isShowing) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
        }
    }
}

// hide keyboard
// works from everywhere
fun Context.hideKeyboardFrom(view: View) {
    val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

// only works when called from Activity
fun Activity.hideKeyboard() {
    val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    //Find the currently focused view, so we can grab the correct window token from it.
    var view = currentFocus
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = View(this)
    }
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

        <activity
            android:name=".views.input.ManualInputActivity"
            android:parentActivityName=".MainActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            // important for button jumping
            android:windowSoftInputMode="adjustResize" >
        </activity>