3

I've seen many questions (and answers) regarding ViewTreeObserver but none have completely answer the question/problem i'm facing. So here's what i have:

I have some views being added programmatically inside a scrollview. After all the layout has been set I want to scroll to a specific view that is inside the scrollview. For this I'm using View Tree Observer and the code is as follows (Some pseudo of what I'm doing)

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

Note: The reason I add firstTime == 3 is because, in this specific case, I noticed that it only calls the global layout 3 times.

So my question is as follows: How can I detect, cleanly, when the Global Layout has finished all the necessary measurements?

Yes I have some work arounds that works like adding a small delay which will give time for the Global Layout to have it's measures done but I was looking for another (cleaner) way to do that.

Any ideas? Thanks!

Peddro
  • 1,105
  • 2
  • 9
  • 19

0 Answers0