App노자

[Android] ViewTreeObserver란 본문

Android/AndroidStudio

[Android] ViewTreeObserver란

앱의노예 2023. 5. 17. 23:13

1. ViewTreeObserver란


ViewTreeObserver란 ViewTree의 변경 사항에 대해 통보받을 수 있는 리스너를 등록하는 데 사용된다.

이러한 이벤트에는 레이아웃, 키보드, 터치 모드 변경 등이 포함되며

ViewTreeObserver는 보기 계층에서 제공하는 응용 프로그램에 의해 인스턴스화되지 않아야 한다

 

https://developer.android.com/reference/android/view/ViewTreeObserver

 

ViewTreeObserver  |  Android Developers

 

developer.android.com

2. 사용방법


        rootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {

                        Rect r = new Rect();
                        rootView.getWindowVisibleDisplayFrame(r);
                        int screenHeight = rootView.getRootView().getHeight();

                        // r.bottom is the position above soft keypad or device button.
                        // if keypad is shown, the r.bottom is smaller than that before.
                        int keypadHeight = screenHeight - r.bottom;


                        if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
                            // keyboard is opened
                            if (!isKeyboardShowing) {
                                isKeyboardShowing = true;
                                onKeyboardVisibilityChanged(true);
                            }
                        }
                        else {
                            // keyboard is closed
                            if (isKeyboardShowing) {
                                isKeyboardShowing = false;
                                onKeyboardVisibilityChanged(false);
                            }
                        }
                    }
                });

이미지 뷰의 ViewTreeObserver를 가져온 뒤, addOnGlobalLayoutListener()를 통해 리스너를 추가해 준다. 여기서 주의할 점은, 옵저버 리스너를 등록한 후 변경 감지를 1회만 할 경우에는 반드시 추가해 준 리스너를 제거해야 한다. 만약 제거를 하지 않은 경우엔 무한 리스너 호출이 생길 수 있다. 리스너 제거는 removeOnGlobalLayoutListener()를 통해 할 수 있다.

'Android > AndroidStudio' 카테고리의 다른 글

[Android] Log확인 - getSimpleName()  (0) 2023.05.31
[Android] TextWatcher  (0) 2023.05.25
[Android] customSelectionActionMode 구현 방법  (0) 2023.04.29
[Android] DialogFragment란  (0) 2023.04.22
[Android] <include> tag  (0) 2023.04.19