Layouting Process什么时候调用onAttachedToWindow

When is onAttachedToWindow called in the Layouting Process

我不确定 onAttachedToWindow 的用法。

我的问题基本上是关于documentation的。 其中提到:

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

我知道什么:

什么时候在onMeasure之前调用,什么时候在之后调用。

背后的故事:

我在 onAttachedToWindow 中添加 OnGlobalLayoutListener 并在 onDetachedFromWindow 中删除它。因为在将视图添加到 window 时处理布局对我来说是合乎逻辑的。 但我担心如果尚未添加监听器,第一个 onGlobalLayout 调用会丢失。 (因为onMeasure一般发生在布局的时候)

如果有人有更好的方法解决我的问题,请随时给我提示。

文档是正确的,您不应该依赖 onWindowAttach/DetachonMeasureonLayout 同步。

如果您的 View class 对父层次结构更改感兴趣,我建议您不要采用这种设计。 Parent UI 应该通知子视图层次结构的变化。因此,OnGlobalLayoutListener 最好由封闭的 UI class.

使用

另外,View class 有 onSizeChanged(),您可以覆盖它以检测它何时被测量。