Challenge2 Not Effective To use OnGlobalLayoutListener


first I applied following codes.

but void onGlobalLayout() function is called several times.

So, When I navigate between crimes through left/right flicking, I can see screen movement is not smooth.
I think this is not so effective.

Do you have any good idea?


Yep, onGlobalLayout() is called 6 times in my case, but I dont see any lags. Nevertheless I have doubts that this is a good solution, because getScaledBitmap() also is called 6 times.
Maybe @cstewart can help us =)


Normally when you use the GlobalLayout listener, you remove the listener the first time that onGlobalLayout is called. This is common because, as you’ve seen, this method gets called a bunch of times and you really only care about when your views are initially configured (which is when onGlobalLayout is first called).

Here’s what I mean:

final ViewTreeObserver observer = mPhotoView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {


it doesn’t work or maybe I do smth wrong.

java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again
at android.view.ViewTreeObserver.checkIsAlive(
at android.view.ViewTreeObserver.removeOnGlobalLayoutListener(
at$7.onGlobalLayout( - observer.removeOnGlobalLayoutListener(this);


Sorry, I just typed up some psuedo-code from how I have done this in the past. I missed a step.

Should be something like this:


Works great!
thx a lot :slightly_smiling_face:


If you add an observer within the OnCreateView method then it will be called multiple times cause CrimeFragment lives inside the ViewPager and ViewPager creates a few fragments at once