Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is onAttachedToWindow called in the Layouting Process

I'm not sure about the usage of onAttachedToWindow.

My question is basically about the documentation. Which mentions:

[...] it may be called any time before the first onDraw -- including before or after onMeasure(int, int)

I what to know:

when it is called before onMeasure and when is it called after.

The Story behind:

I am adding OnGlobalLayoutListener in onAttachedToWindow and remove it in onDetachedFromWindow. Because is somehow logic to me to handle the layouting when the view is added to the window. But I am concerned that the first onGlobalLayout calls get lost, if the Listener is not added yet. (because onMeasure usually happens during the layouting)

If someone got a better approach for my problem, feel free to give me a hint.

like image 360
foxy Avatar asked Oct 26 '25 11:10

foxy


1 Answers

Docs are correct, and you should not rely on onWindowAttach/Detach being in sync with onMeasure or onLayout pass.

If your View class is interested in parent hierarchy changes, I'd advice against such a design. The Parent UI should notify sub-views of hierarchy changes. So, OnGlobalLayoutListener better be used by an enclosing UI class.

Also, View class has onSizeChanged() that you can override to detect when it has been measured up.

like image 67
S.D. Avatar answered Oct 28 '25 23:10

S.D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!