awesome-kotlin-extensions icon indicating copy to clipboard operation
awesome-kotlin-extensions copied to clipboard

Keyboard Extension

Open pooja-srivs opened this issue 5 years ago • 1 comments

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

pooja-srivs avatar Oct 07 '20 11:10 pooja-srivs

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)
    }
}

thuijssoon avatar Jan 28 '21 09:01 thuijssoon