可以分三個步驟:
1. 繼承 (extends)
挑個最接近的既有元件來擴充
不過如果沒有可達到需求的類別的話
就只能繼承 View 或 ViewGroup 自己寫...
2. 改寫 (override)
除了兩個 constructor 要改寫外
(一個是傳入 Context, 另一個的傳入參數是Context 跟 AttributeSet
還要改寫 onDraw, onMeasure 改變外觀、onTouchEvent, onKeyDown 改變行為...等
(關於 onMeasure 文件裡有一些說明
改寫此方法時,必須呼叫 setMeasuredDimension(int, int) 來儲存測量過的寬與高。如果沒這麼做,measure(int, int)這個方法會丟出 IllegalStateException。Calling the superclass' onMeasure(int, int) is a valid use.
如果要改寫此方法,就必須負責確認測量過的寬與高必須大於等於這個 view 的最小寬高(getSuggestedMinimumHeight() and getSuggestedMinimumWidth())
可以改寫的方法有:
Category | Methods | Description |
---|---|---|
Creation | Constructors | There is a form of the constructor that are called when the view is created from code and a form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file. |
| Called after a view and all of its children has been inflated from XML. | |
Layout |
| Called to determine the size requirements for this view and all of its children. |
| Called when this view should assign a size and position to all of its children. | |
| Called when the size of this view has changed. | |
Drawing |
| Called when the view should render its content. |
Event processing |
| Called when a new key event occurs. |
| Called when a key up event occurs. | |
| Called when a trackball motion event occurs. | |
| Called when a touch screen motion event occurs. | |
Focus |
| Called when the view gains or loses focus. |
| Called when the window containing the view gains or loses focus. | |
Attaching |
| Called when the view is attached to a window. |
| Called when the view is detached from its window. | |
| Called when the visibility of the window containing the view has changed. |
3. 替換 (place of)
在 layout 的 xml 裡使用它
記得要使用 full package name
範例:API Demos 裡的 LabelView 類別
複合式組件
(也就是把原有組件組合起來的)
一般是擴充自 layout 類型
改寫方法是在 constructor 裡第一步先呼叫 super 把參數傳出
接著設定 component 裡面的 view
以及定義一些 XML 的自定義屬性
如果是繼承自 Layout 類型,基本上不用改寫 onDraw, onMeasure
因為子組件都運作得很好了
範例:API Demos 裡的 List4.java and List6.java.
參考資料:
Android Developer - Custom Components
沒有留言:
張貼留言