標籤雲

搜尋此網誌

2013/04/03

客製化元件 (Building Custom Component) 入門

客製化元件當然最省力的方法就是繼承已有的類別

可以分三個步驟:

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())

可以改寫的方法有:
CategoryMethodsDescription
CreationConstructorsThere 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.
onFinishInflate()Called after a view and all of its children has been inflated from XML.
LayoutonMeasure(int, int)Called to determine the size requirements for this view and all of its children.
onLayout(boolean, int, int, int, int)Called when this view should assign a size and position to all of its children.
onSizeChanged(int, int, int, int)Called when the size of this view has changed.
DrawingonDraw(Canvas)Called when the view should render its content.
Event processingonKeyDown(int, KeyEvent)Called when a new key event occurs.
onKeyUp(int, KeyEvent)Called when a key up event occurs.
onTrackballEvent(MotionEvent)Called when a trackball motion event occurs.
onTouchEvent(MotionEvent)Called when a touch screen motion event occurs.
FocusonFocusChanged(boolean, int, Rect)Called when the view gains or loses focus.
onWindowFocusChanged(boolean)Called when the window containing the view gains or loses focus.
AttachingonAttachedToWindow()Called when the view is attached to a window.
onDetachedFromWindow()Called when the view is detached from its window.
onWindowVisibilityChanged(int)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

沒有留言: