mahesmohan
mahesmohan

Reputation: 804

Show keyboard when an EditText gains focus and hide keyboard when it loses focus

The question is self explanatory.

Show soft keyboard when your edit text gains focus and hide keyboard when it loses focus. Here is the code that I have used.

this.newTaskTitle = (EditText) taskCreationView.findViewById(R.id.newTaskTitle);
    this.newTaskTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            //Set up input manager
            InputMethodManager keyboardManager = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE
            );
            if(hasFocus) {
                Log.i(TAG,"hasFocus");
                //Display keyboard
                keyboardManager.showSoftInput(
                        v,
                        InputMethodManager.SHOW_IMPLICIT
                );
            } else {
                Log.i(TAG,"lostFocus");
               //Hide keyboard
                keyboardManager.hideSoftInputFromInputMethod(
                        v.getWindowToken(),
                        0
                );
            }
        }
    });

Even though the else executes when the EditText loses focus, the keyboard is never hidden. Why would that be ?

Isn't this the right way to hide the keyboard ?

Upvotes: 1

Views: 1690

Answers (1)

Ali
Ali

Reputation: 1915

I think, there is no need to set OnFocusChangeListener. Call below method from onClick of your button and after calling this method set visibility GONE of your EditText.On gaining focus soft keyboard get open automatically.

private  void hideKeyBoard(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

Upvotes: 1

Related Questions