williamsandonz
williamsandonz

Reputation: 16420

Android hide keyboard on off focus but not when password field selected

The code below works when I off focus to another textField but not when I just tap anywhere on the screen (which I'd like to trigger the onFocusChanged event). How can I achieve this? I'll also need to check that the other textfield doesnt't have focus, because if it does the keyboard should be retained.

usernameET.setOnFocusChangeListener((new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(v == usernameET) {
                    Log.d(LoginPage.Tag, "keyboardOnTouch");
                    if (hasFocus)
                    {
                        ((InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(usernameET,
                                InputMethodManager.SHOW_FORCED);
                    }
                    else {
                        ((InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                                usernameET.getWindowToken(), 0);
                    }
                }
            }
        }));

Upvotes: 0

Views: 212

Answers (1)

KDeogharkar
KDeogharkar

Reputation: 10959

You can use the onTouchEvent() to hide the Softkeyboard.

@Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
                                                        INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }

Hope this will help.

Upvotes: 1

Related Questions