概览:
- View 的生命周期
- Traversals
- Measure
- Draw
- Custom Attributes
- 监听事件很简单,不讲了
- 状态保存
- 参考链接
1. View 的生命周期
- Attachment/detachment(一般不用care)
- Traversals(必须care)
- State save/restore(看你的需求了)
Attachment的回调接口是onAttachedToWindow()
,在这里你可以做以下操作
- Call super.onAttachedToWindow()!
- Perform any relevant state resets
- Start listening for state changes
detachment的回调接口是onDetachedFromWindow()
,在这里你可以做以下操作
- Call super.onDetachedFromWindow()!
- Remove any posted Runnables
- Stop listening for data changes
- Clean up resources
- Bitmaps
- Threads
看看官方的SwipeRefreshLayout
的运用
|
|
打个简单地比喻就是,如果你的View和网络操作相关的话,最好在这里做取消操作。它这里的操作其实就是取消或重置动画。好了,这里就不多说了,一般用不到。下面说说遍历Traversals。
2. Traversals
Traversals 分四个阶段
Animate—>Measure—>Layout—>Draw
我们现在关心的是Measure和Draw,分别对应onMeasure()
,onDraw()
,先看看View的默认实现吧。
|
|
现在来看看具体的Measure
3. Measure
如果你自定义的View没有特殊尺寸要求的话,也可以不重写onMeasure()
。现在来说说比较难理解的MeasureSpec 模式,三张图搞定它
在onMeasure()
里由于没有回调,框架依赖你最后设置尺寸,所以你一定要调用setMeasuredDimension()
,否则运行时会crash。
看看大牛Dave Smith 给的一个模板吧:
|
|
工具方法
|
|
4. Draw
这其实没有太多要说的,onDraw()
回调已经给你了一个Canvas,你要做的就是画各种你需要的东西了。看看Canvas的官方定义吧:
The Canvas class holds the “draw” calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).
这里的Canvas已经包含一个mutable 的Bitmap了。需要注意的是onDraw()
调用的很频繁,实例化对象的操作应该都放到外面。随便看个例子吧:
|
|
其实这里的获取宽高的操作应该放到onSizeChanged()
里面,这个是在onLayout()
里调用的,而且一般只遍历一次。
5. Custom Attributes
这个没什么要讲的,看例子就理解了。
|
|
下面这段好好理解
Given the attrs.xml in Listing 1-18, Android generates the following IDs:
|
|
在初始化时
|
|
DON’T FORGET: TypedArrays are heavyweight objects that should be recycled immediately after all the attributes you need have been extracted.
6. 监听事件很简单,不讲了
7. 状态保存
用系统的方式保存状态,万无一失,下面看模板:
|
|
注意:你需要在初始化时,调用this.setSaveEnabled(true);
,当然,状态保存也不是必须的,看你的需求了。
8. 参考链接
https://www.youtube.com/watch?v=NYtB6mlu7vA
https://thenewcircle.com/s/post/1663/tutorial_enhancing_android_ui_with_custom_views_dave_smith_video
https://dl.dropboxusercontent.com/u/16714463/Google%20IO%202014/Material%20Witness.pdf
http://developer.android.com/training/custom-views/index.html
http://developer.android.com/guide/topics/ui/custom-components.html
《Expert Android》