简体   繁体   中英

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.

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.

To show keyboard,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

If you want to focus to a editText, use

editText.requestFocus();

To hide keyboard,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM