ch8n / awesome-kotlin-extensions

A curated collection of awesome Kotlin extensions android/non-android. :octocat:
23 stars 6 forks source link

Keyboard Extension #1

Open pooja-srivs opened 3 years ago

pooja-srivs commented 3 years ago

Add extension for keyboard

require following functions

  1. extension for show keyboard
  2. extension for hide keyboard

Acceptance

need to be compatible with new keyboard api

How did you tested the extension?

please mention how did you tested the extension and save to use while generating the PR

thuijssoon commented 3 years ago

How about something like this:

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment

/**
 * Hide the soft keyboard if visible
 */
fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

/**
 * Hide the soft keyboard if visible
 */
fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
}

/**
 * Hide the soft keyboard if visible
 */
fun Context.hideKeyboard(view: View) {
    val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    view.clearFocus()
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

/**
 * Show the soft keyboard for this EditText.
 * Will request focus and move the cursor to the end.
 */
fun EditText.showKeyboard() {
    if (this.requestFocus()) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        this.setSelection(this.text.length);
        imm.showSoftInput(this, 0)
    }
}