Why we use ViewTreeObserver#addOnGlobalLayoutListener()

Prasanth Yejje picture Prasanth Yejje · Apr 26, 2017 · Viewed 13.1k times · Source

Why do we use ViewTreeObserver, please can anyone explain it?

In below code creditsView is TextView object. By this whole code I understand that "this is to hide some text based on condition", but only thing is why we are using ViewTreeObserver?

mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = mainLayout.getRootView().getHeight() - mainLayout.getHeight();

            if (heightDiff > 100) {
                Utils.appLogger("MyActivity", "keyboard opened");
                creditsView.setVisibility(View.GONE);
            }

            if (heightDiff < 100) {
                Utils.appLogger("MyActivity", "keyboard closed");
                creditsView.setVisibility(View.VISIBLE);
            }
        }
    });

Answer

azizbekian picture azizbekian · Apr 26, 2017

If you hadn't used ViewTreeObserver, than mainLayout.getRootView().getHeight() would simply return 0px, because it hasn't been laid out yet (see getWidth() and getHeight() of View returns 0).

Thus, you are waiting until view is measured, laid out, and then you are fetching width/height values from it. This callback will be fired exactly when the view is going to be laid out on the screen.