Android onAttachedToWindow的应用场景介绍

本文探讨了Android中onAttachedToWindow()函数在Activity生命周期中的位置,指出它在onCreate->onStart->onResume之后。通过实验和源码分析,解释了为何要在onAttachedToWindow中而非onCreate中修改窗口尺寸,原因是onAttachedToWindow后DecorView的LayoutParams已设置,避免了空指针异常。同时,文中强调在onAttachedToWindow进行窗口尺寸修改的稳定性。
摘要由CSDN通过智能技术生成

若需实现圆角对话框Activity,需要在Activity的onAttachedToWindow()函数中做文章,那么就想问:

  • onAttachedToWindow在整个Activity的生命周期中占据什么位置?
  • 为什么要在onAttachedToWindow中修改窗口尺寸?

 

一、onAttachedToWindow在Activity生命周期中的位置

根据之前分析API的套路,看onAttachedToWindow在Android文档中怎样介绍。

首先看Window.Callback中关于onAttachedToWindow的介绍。

public abstract void onAttachedToWindow ()

Called when the window has been attached to the window manager. See View.onAttachedToWindow() for more information.

好吧,官方把我引导到了View中,那么恭敬不如从命,看View中怎么说。

protected void onAttachedToWindow ()

 

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called beforeonDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

从API说明我们可以定位当View附加到窗体时,也就是View和Window绑定时就会调用这个函数,此时将会有一个Surface进行绘图之类的逻辑。并且发现Window.CallBack是一个接口类,而且官方引导到了View中,那么可以大胆判断View实现了Window.CallBack的回调方法,那么View和Window之间的关系便可以有个初步猜测。下篇博客再具体讨论DecorView和Window之间的关系。

接下来通过实验判断onAttachedToWindow在Activity整个生命周期中的位置。

实验很简单,将Activity各个生命周期打上log,然后看LogCat中的结果

看来我们最终要找的生命周期为onCreate->onStart->onResume->onAttachedToWindow

 然后通过Google找到了一张比较详细的Activity生命周期图,也印证了我们的实验结论。

详见http://staticfree.info/~steve/complete_android_fragment_life

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值