The best work around I found was using as below,
Override dispatchTouchEvent()
and try to get the area of EditText
using Rect
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getX();
int y = (int) ev.getY();
if (ev.getAction() == MotionEvent.ACTION_DOWN &&
!getLocationOnScreen(etFeedback).contains(x, y)) {
InputMethodManager input = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(etFeedback.getWindowToken(), 0);
}
return super.dispatchTouchEvent(ev);
}
Method that caculates 4 corner of View(here its EditText)
protected Rect getLocationOnScreen(EditText mEditText) {
Rect mRect = new Rect();
int[] location = new int[2];
mEditText.getLocationOnScreen(location);
mRect.left = location[0];
mRect.top = location[1];
mRect.right = location[0] + mEditText.getWidth();
mRect.bottom = location[1] + mEditText.getHeight();
return mRect;
}
By using above code we can detect the area of EditText
and we can check if the touch on the screen is part of the area of EditText
or not. If its part of EditText
then don't do anything let the touch do its job, and if the touch doesn't contain area of EditText
then just close the softkeyboard.
******EDIT******
I just found another approach if we don't want to give any EditText as input and want to hide keyboard inside whole application when user touches anywhere else other than EditText. Then you have to create an BaseActivity and write global code for hiding keyboard as below,
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handleReturn = super.dispatchTouchEvent(ev);
View view = getCurrentFocus();
int x = (int) ev.getX();
int y = (int) ev.getY();
if(view instanceof EditText){
View innerView = getCurrentFocus();
if (ev.getAction() == MotionEvent.ACTION_UP &&
!getLocationOnScreen(innerView).contains(x, y)) {
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return handleReturn;
}