addOnLayoutChangeListener vs addOnGlobalLayoutListener vs post(Runnable r)
Asked Answered
S

1

13

PROBLEM: Suppose we have simple case: we have view and we have to show some data on this view. We use static method showData(View view) to do this. I want to know the exact moment when view layout is measured and I can access getWidth() getHeight() and be sure that this is final width and height of my view.

WHAT I KNOW: (not sure I am 100% right):

I know 3 different approaches to do this

  • view.addOnLayoutChangeListener - we know when layout is changed, we can get height and width
  • view.getViewTreeObserver().addOnGlobalLayoutListener - for my case almost the same, but we get information later. Because layoutChange bubbles from children to root, and globalLayout from root to children (right?).
  • view.post(Runnable r) - is working, but I do not know why runnable is posted to ui thread executes after view is measured.

QUESTION: What is the best approach to know that view is measured? and why?

Spindell answered 31/5, 2015 at 4:7 Comment(0)
F
1

What is the best approach to know that view is measured?

The best Approach? OnGlobalLayoutListener with View.getMeasuredHeight() or View.getMeasuredWidth()

and why?

Because your mom knows you better than you know yourself, so its better to consult the ViewGroup about its state which automatically speaks volumes about the children.

View.post() enqueues process on the ui queue. Ui queue ={1,2}, later after you call that line = {1,2,runnable}. so definitely it will run after 1,2

Fellmonger answered 31/5, 2015 at 5:23 Comment(2)
thank u:) but onLayoutChange is also invoked by parent viewgroup, so why OnGlobalLayoutListener is better choise? I also wondering about View.post(). So if i have call to method showData(View view) and next line is view.post(Runnable r) so runnable will be executed after view is measured and has exact layout? I mean view.post(r) cannot happen between showData(View v) and onMeasure?Spindell
when you call View.Gone on a child the ViewGroup will trigger onGlobalLayoutListener which might call onlayoutchange, that's when the bounds change, on globalLayout is the state of the family, if one changes the mother is notified, when you use object animator to animate the view it will be triggered,just an example so if you really want to monitor you will need to use it, and not they get called often, view.post() like i said enqueues it so there might be the case that it will always fall behind os initial defined calls, @Spindell hope it helpsFellmonger

© 2022 - 2024 — McMap. All rights reserved.