I am currently showing softkeyboard using the following code
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im
// Simple, reuseable call anywhere in code
myView.hideKeyboard()
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun View.showKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}
Simplify adding Done
/Next
... action to edittext: read this post
Remove requirement for ever using getSystemService
: Splitties Library
If you want, you can use entire class and call KeyboardUtil.hideKeyBoard(context) method wherever:
public class KeyboardUtil
{
public static void hideKeyboard(Activity activity)
{
try
{
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
catch (Exception e)
{
// Ignore exceptions if any
Log.e("KeyBoardUtil", e.toString(), e);
}
}
}
InputMethodManager im =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
For hiding keyboard,
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
Here, “mView” can be any view which is visible on screen
Here is s solution, which checks if keyboard is visible
public static void hideKeyboard(Activity activity) {
if (isKeyboardVisible(activity)) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
public static boolean isKeyboardVisible(Activity activity) {
///This method is based on the one described at http://stackoverflow.com/questions/4745988/how-do-i-detect-if-software-keyboard-is-visible-on-android-device
Rect r = new Rect();
View contentView = activity.findViewById(android.R.id.content);
contentView.getWindowVisibleDisplayFrame(r);
int screenHeight = contentView.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
return
(keypadHeight > screenHeight * 0.15);
}
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
it's working for me i hope it's work for you..
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}