addOnLayoutChangeListener vs addOnGlobalLayoutListener vs post(Runnable r)

萝らか妹 提交于 2019-12-01 14:33:58

问题


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?


回答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



来源:https://stackoverflow.com/questions/30553745/addonlayoutchangelistener-vs-addongloballayoutlistener-vs-postrunnable-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!