When we have an EditText and it loses focus (to an element that doesn\'t need a keyboard), should the soft keyboard hide automatically or are we supposed to hid
You can override the dispatchTouchEvent method to achieve it:
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
/**
* It gets into the above IF-BLOCK if anywhere the screen is touched.
*/
View v = getCurrentFocus();
if ( v instanceof EditText) {
/**
* Now, it gets into the above IF-BLOCK if an EditText is already in focus, and you tap somewhere else
* to take the focus away from that particular EditText. It could have 2 cases after tapping:
* 1. No EditText has focus
* 2. Focus is just shifted to the other EditText
*/
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
Bonus: In case of an EditText gaining focus, the order of event triggered is:
onFocusChange() of another EditText is called (if that other edittext is losing focus)ACTION_DOWN is calledonFocusChange() method of that EditText will get called.