방명록
- [Android] EditText 바깥 영역 터치 시 키보드를 숨기기2023년 10월 25일 22시 16분 00초에 업로드 된 글입니다.작성자: 핀수728x90반응형
Kotlin
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { val currentFocusView: View? = currentFocus if (currentFocusView != null && (ev?.action == MotionEvent.ACTION_UP) || ev?.action == MotionEvent.ACTION_MOVE && currentFocusView is EditText && currentFocusView.javaClass.name.startsWith("android.webkit.")) { val scored = IntArray(2) currentFocusView.getLocationOnScreen(scored) val x: Float = ev.rawX + currentFocusView.left - scored[0] // 0은 마지막 터치 위치에서 x값 val y: Float = ev.rawY + currentFocusView.top - scored[1] // 1은 마지막 터치 위치에서 y값 if (x < currentFocusView.left || x > currentFocusView.right || y < currentFocusView.top || y > currentFocusView.bottom) (this.getSystemService( INPUT_METHOD_SERVICE ) as InputMethodManager).hideSoftInputFromWindow( this.window.decorView.applicationWindowToken, 0 ) } return super.dispatchTouchEvent(ev) }
Java
/** * editText 가 아닌 곳을 클릭 시 키보드 숨기기 * * @param ev MotionEvent * @return ev */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { View view = getCurrentFocus(); // 현재 터치 위치 if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText // view 의 id 가 명시되어있지 않은 다른 부분을 터치 시 && !view.getClass().getName().startsWith("android.webkit.")) { int[] scored = new int[2]; view.getLocationOnScreen(scored); float x = ev.getRawX() + view.getLeft() - scored[0]; // 0은 마지막 터치 위치에서 x값 float y = ev.getRawY() + view.getTop() - scored[1]; // 1은 마지막 터치 위치에서 y값 if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom()) ((InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0); } return super.dispatchTouchEvent(ev); }
결과
해당 코드를 적용하지 않았을 때
해당 코드를 적용했을 때
728x90반응형'pinslog > Log.daily()' 카테고리의 다른 글
[git] 머지 취소하기 (0) 2023.10.28 [Android] 로컬 프로젝트를 implementation하기 (0) 2023.10.26 [Kotlin] 함수 탈출하기 (0) 2023.10.21 튼튼한 집 짓기 (0) 2023.10.19 [Android] compileSdk 32 to 33 issue (0) 2023.10.18 다음글이 없습니다.이전글이 없습니다.댓글