Skip to content

Instantly share code, notes, and snippets.

@sc0rch
Created July 9, 2016 01:45
Show Gist options
  • Save sc0rch/7c982999e5821e6338c25390f50d2993 to your computer and use it in GitHub Desktop.
Save sc0rch/7c982999e5821e6338c25390f50d2993 to your computer and use it in GitHub Desktop.
Clear focus on touch outside for all EditText inputs.
public class MainActivity extends Activity
// ... any code
/**
* Clear focus on touch outside for all EditText inputs.
*/
@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())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
}
@onelessangel
Copy link

worked wonderfully! helped me out so much, ty!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment