本文介绍了为什么我们使用ViewTreeObserver#addOnGlobalLayoutListener()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们为什么使用ViewTreeObserver,请任何人解释一下吗?

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

在下面的代码中,creditsViewTextView对象.通过整个代码,我了解到这是根据条件隐藏一些文本",但是唯一的原因就是为什么我们使用ViewTreeObserver?

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);
            }
        }
    });

推荐答案

如果您未使用ViewTreeObserver,则mainLayout.getRootView().getHeight()只会返回0px,因为尚未进行布局(请参见 getWidth()View中的getHeight()返回0 ).

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.

这篇关于为什么我们使用ViewTreeObserver#addOnGlobalLayoutListener()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 13:27