Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show keyboard programmatically Android

Is there a way to show keyboard in an Activity above Android O version ? I have the following code :

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

It works 'only' for below Android O Version.

like image 202
itsmebil Avatar asked Apr 08 '26 04:04

itsmebil


2 Answers

I got 2 options for you. First, you can use RequestFocus

editText.requestFocus();

Second, you can execute this code to show the keyboard for a specific EditText

android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);

Extra point, use this to hide the keyboard:

android.view.View view = this.getCurrentFocus();   
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

Note: every code here is tested and working.

like image 194
Regex Avatar answered Apr 10 '26 18:04

Regex


For kotlin extension function and reusable

fun View.hideKeyboard() {
    ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())
}

fun View.showKeyboard() {
    ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
}

fun View.showKeyboardAndFocus() {
    ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
    requestFocus()
}
like image 28
snorlax Avatar answered Apr 10 '26 19:04

snorlax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!