Wednesday, April 15, 2015

How to hide the virtual keypad by clicking outside of an EditText

There is the difference in the Keypad behavior between Android and IOS. When user clicks on Edit box, a virtual keypad pops up. But when we are done with the editing or to make this soft keyboard hide, we need to click on  "Done" or "Next" button of the keyboard or we need to click on the Back button of the Android in all the Android devices.

But in IOS devices, the behavior is different.  To make the keyboard hide, we can click on the screen of the phone anywhere outside the edit box.  In Android until and unless we click on done or next button or the back button keypad does not go away. This behavior of android is annoying if you are the adjusted to the use of IOS devices.

So when we were working on an android application, the customer asked us to make the behavior of the android keyboard same as that of IOS in the application. So here is the solution for this.

If you are using the edit box in an activity, you can use the below code snippet :

@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;

}


Override this method where you have the edit box in the activity. If we remove the coordinate checks, the keyboard does not come up next time when we click on the edit box.

Below is the code which actually does the trick:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

We need to wrap it around the dispatchTouchEvent() as shown above.If you are using the edit box in the fragments, you need to add the above method in FragmentManager. That's all. All the best and happy coding. (y)

No comments: