Challenge2 Not Effective To use OnGlobalLayoutListener


#1

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?


#2

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 =)


#3

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() {
    @Override
    public void onGlobalLayout() {
        ...
        observer.removeOnGlobalLayoutListener(this);
    }
});

#4

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(ViewTreeObserver.java:817)
at android.view.ViewTreeObserver.removeOnGlobalLayoutListener(ViewTreeObserver.java:564)
at com.bignerdranch.android.criminalintent.CrimeFragment$7.onGlobalLayout(CrimeFragment.java:230)

CrimeFragment.java:230 - observer.removeOnGlobalLayoutListener(this);


#5

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: https://stackoverflow.com/a/26193736/5664832


#6

Works great!
thx a lot :slightly_smiling_face:


#7

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