3

There are a lot of tips on Stackoverflow on how to wait the moment when View is inflated and measured. Most of them boil down to need to use View.post () or OnGlobalLayoutListener. In my custom views I use the onSizeChanged () method, in which I get dimensions if necessary. How exactly does View.post () work in such cases? Does it guarantee that View considers its size? Is this a workaround?

badadin
  • 507
  • 1
  • 5
  • 18
  • 3
    All `post()` does is put a `Runnable` onto the main application thread's `Looper` work queue, to be processed in turn. There are no guarantees about the state of the view hierarchy at the time that `Runnable` is run. – CommonsWare Jan 19 '19 at 18:51
  • @CommonsWare, So all those advices are just workaround? – badadin Jan 19 '19 at 18:54
  • `post()` usually is a workaround. It may be good enough for some situations. – CommonsWare Jan 19 '19 at 18:57
  • Any examples of these situations? – badadin Jan 19 '19 at 18:59
  • @CommonsWare, You should note in your The Busy Coder's Guide that this is not a silver bullet when solving view inflating problems :) Because many developers use post() for that purpose. – badadin Jan 19 '19 at 19:18
  • 7
    "Any examples of these situations?" -- I don't have a concrete one handy. Generally, it seems safe when the only thing that you care about is that the work happens a bit later on the main application thread. In general, something more concrete is better. [Android KTX's `doOnLayout()`](https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#doonlayout) and `doOnNextLayout()` are good examples of more concrete timing that winds up being as easy to use (or easier) than `post()`. – CommonsWare Jan 19 '19 at 19:33
  • Thank you for quite a comprehensive answer – badadin Jan 19 '19 at 19:42

0 Answers0