Search code examples
androidandroid-edittextkeyboardcustomdialog

Hide soft Keyboard in Android after a custom dialog dismiss


I'm in a situation in which I have an editText. When I press add in the edit text i'm adding a member in a list. When is added (or not) I'm opening a custom Dialog.

In my activity i have this code when clicking on add button in the edit text:

  customDialogTeamMember = new CustomDialogTeamMember(............);
  customDialogTeamMember.makeDialog();
  editText.getText().clear();
  editText.clearFocus();
  hideSoftKeyboard();

My hideSoftKeyboard() is defined like:

public void hideSoftKeyboard() {
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

This method works in other sections of the app. But here is not working!

The custom dialog opens. When i close it the keyboard keeps on the screen. What could be the problem?!


Solution

  • To show and hide Keyboard

    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Hide:
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    //Show
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    
    
    
    
    private void hideKeyboard() {   
        // Check if no view has focus:
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    
    private void showKeyboard() {   
        // Check if no view has focus:
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }