본문 바로가기

Android

[Android] EditText가 아닌 다른 곳 클릭시 키보드 내리기

public class MainActivity extends AppCompatActivity {
...
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        View focusView = getCurrentFocus();
        if (focusView != null) {
            Rect rect = new Rect();
            focusView.getGlobalVisibleRect(rect);
            int x = (int) ev.getX(), y = (int) ev.getY();
            if (!rect.contains(x, y)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (imm != null)
                    imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
                focusView.clearFocus();
            }
        }
        return super.dispatchTouchEvent(ev);
    }
...

현재 Focus를 받고 있는 View의 영역이 아닌 다른 곳에 터치 이벤트가 일어나면 InputMethodManager을 통해 키보드를 내리는 코드입니다.

 

TouchEvent의 흐름에 대해 궁금하신 분들은 아래 StackOverFlow의 글을 참고해주세요.

https://stackoverflow.com/questions/7449799/how-are-android-touch-events-delivered

 

How are Android touch events delivered?

I'm not asking how to handle touch events, but what is going on behind the scenes? If there are several nested widgets, what order do they see the events in? Does the developer have any control ove...

stackoverflow.com