Search code examples
androidkeyboard

Hide Android soft keyboard if it is open


I have three edit-text fields. Of these fields I want to display the soft input keyboard only for the first field and disabled for the later two fields sice these are date and time fields.

Edit-Text 1 //Show the keyboard
Edit-Text 2 and 3 //Hide the keyboard

By using below code I'm able to disable the keyboard for field 2 and 3 but when the user has focus on field 1 the keyboard appears but didn't hide when user taps on field 2 or 3. Although when field 2 or 3 is tapped first no keyboard appears.

//Code to disable soft input keyboard
public static void disableSoftInputFromAppearing(EditText editText) {
    if (Build.VERSION.SDK_INT >= 11) {
        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
        editText.setTextIsSelectable(true);
    } else {
        editText.setRawInputType(InputType.TYPE_NULL);
        editText.setFocusable(true);
    }

How can I hide the soft input keyboard if its already open?


Solution

  • //activity

    public static void hideSoftKeyboard(Activity activity) {
    
       InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
       inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
     }
    

    // fragment

    public void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
    }
    

    // If edit-text loses the focus, hiding keyboard

    edTxtMessage.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isEditable){
                    v.setFocusable(true);
                    v.setFocusableInTouchMode(true);
                } else {
                    edTxtMessage.setFocusable(false);
                }
    
                return false;
            }
        });
    
    edTxtMessage.setOnFocusChangeListener(new View.OnFocusChangeListener({
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b){
                    hideKeyboard(getContext(), view);
                }
            }
        });
    
    private void hideKeyboard(Context context, View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }