Skip to content

Instantly share code, notes, and snippets.

@Tanapruk
Created June 23, 2017 04:50
Show Gist options
  • Save Tanapruk/7f11982a0519642c4d73e910f3905ccd to your computer and use it in GitHub Desktop.
Save Tanapruk/7f11982a0519642c4d73e910f3905ccd to your computer and use it in GitHub Desktop.
Unfocus EditText when taping outside
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.d("focus", "focus loosed");
// Do whatever you want here
} else {
Log.d("focus", "focused");
}
}
});
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
Log.d("focus", "touchevent");
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(event);
}
//in the layout above
<LinearLayout ...
android:focusable="true"
android:focusableInTouchMode="true"
...>
<EditText..></EditText>
</LinearLayout..>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment