Reputation: 21
HideKeyboard method not working when dialog is open in other cases works fine.
I tried every popular hideKeyboard method on stack non of them works.
fun hideKeyboard(activity: Activity) {
if(activity == null) return
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.hideSoftInputFromWindow(activity.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
I am not getting any error but keyboard won't close.
Upvotes: 1
Views: 723
Reputation: 350
HideKeyboard function Android Code
public void hideKeyboard(View view, Context context) {
try {
if (view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception Ex) {
}
}
Upvotes: 1
Reputation: 393
public void hideKeyboard(View view, Context context) {
try {
if (view != null) {
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception Ex) {
}
}
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Conclusions first you call hide method and after that Dialog.So When call hide method then hide keyboard and and again calling Dialog after call dialog then open.
Upvotes: 0
Reputation: 759
If you're using AlertDialog then you can do this as below. You can get getWindow() from alertDialog
object
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Upvotes: 1
Reputation: 2504
Try this
public static void hideKeyboardFrom(Context context, View view)
{
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
For kotlin
fun hideKeyboard(context : Context, view : View)
{
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
Upvotes: 1