3

我看过很多关于 ViewTreeObserver 的问题(和答案),但没有一个完全回答我面临的问题/问题。所以这就是我所拥有的:

我在滚动视图中以编程方式添加了一些视图。设置完所有布局后,我想滚动到滚动视图内的特定视图。为此,我使用 View Tree Observer,代码如下(我正在做的一些伪)

viewInsideScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public synchronized void onGlobalLayout() {
                firstTime++; // Counts how many times I enter the listener
                if (firstTime == 1) {
                    // Here the fully measure of the scroll view has not happened
                } else if (firstTime == 2) {
                    // I still don't have the full measure of the scroll view (Let's say that, for example, paddings are missing/weren't calculated)
                } else if (firstTime == 3) {
                    // Here is when I can safely get the locationOfTheView variable and the scroll down will happen perfectly!
                    viewInsideScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    scrollView.scrollTo(0, locationOfTheView);
                }
            }
        });

注意:我添加的原因firstTime == 3是,在这种特定情况下,我注意到它只调用了全局布局 3 次。

所以我的问题如下:我怎样才能干净地检测全局布局何时完成所有必要的测量?

是的,我有一些解决方法,比如添加一个小的延迟,这将为全局布局提供时间来完成它的措施,但我正在寻找另一种(更清洁)的方法来做到这一点。

有任何想法吗?谢谢!

4

0 回答 0