Advertisement
retnet

hide keyboard on touch outside

Apr 12th, 2020
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1.  @Override
  2.     public boolean dispatchTouchEvent(MotionEvent event) {
  3.         View view = getCurrentFocus();
  4.         boolean retnet = super.dispatchTouchEvent(event);
  5.         if (view instanceof EditText) {
  6.             View w = getCurrentFocus();
  7.             int[] scrcoords = new int[2];
  8.             assert w != null;
  9.             w.getLocationOnScreen(scrcoords);
  10.             float x = event.getRawX() + w.getLeft() - scrcoords[0];
  11.             float y = event.getRawY() + w.getTop() - scrcoords[1];
  12.  
  13.             if (event.getAction() == MotionEvent.ACTION_UP
  14.                     && (x < w.getLeft() || x >= w.getRight()
  15.                     || y < w.getTop() || y > w.getBottom()) ) {
  16.                 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  17.                 assert imm != null;
  18.                 imm.hideSoftInputFromWindow(Objects.requireNonNull(getWindow().getCurrentFocus()).getWindowToken(), 0);
  19.             }
  20.         }
  21.         return retnet;
  22.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement