awesome-kotlin-extensions
awesome-kotlin-extensions copied to clipboard
Keyboard Extension
Add extension for keyboard
require following functions
- extension for show keyboard
- 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
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)
}
}