0

For closing the keypad when touches or clicks the outside of the Edittext, i followed the below code. if there is one edittext its working correctly but more than one its not working.

Example Scenario:

Step 1 : Clicking the first edittext it opens the keypad. Step 2 : Clicking outside of the first edittext it closes the keypad. Step 3 : Clicking the second edittext it doesn't open the keypad.

i think it consider second edittext as a outside of first edittext. i dont know really... can someone please help me...

and this code is for all edittext field in a activity we can use, we can do by using specific edittext also, but i don't want to find a outside clicks or touches of a specific edittext.

        @Override
        public boolean dispatchTouchEvent(MotionEvent event) {
        View view = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (view instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP 
        && (x < w.getLeft() || x >= w.getRight() 
        || y < w.getTop() || y > w.getBottom()) ) { 
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
        return ret;
        }
user3546693
  • 364
  • 3
  • 18

1 Answers1

0

Please try with following code:

public static void hideSoftKeyboard(Activity activity) {

    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager.isAcceptingText()) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                0);//You need to change the focus here to another view for hide the keyboard.
    }

}

You need to call the above method as follows : Here we are checking that if edittext object has focus then call below method.

if (etSeach.hasFocus()) {
                        hideSoftKeyboard(ViewTaskActivity.this);
                    }
Rajan Bhavsar
  • 1,977
  • 11
  • 25