Custom Views

Built-in widgets/components/views in Android include

  1. Button

  2. TextView

  3. EditText

  4. ListView

  5. CheckBox

  6. RadioButton

  7. Gallery

  8. Spinner

  9. AutoCompleteTextView

  10. Image Switcher

  11. Text Switcher

→ If the built-in views don't meet your requirements, you can create your own View subclass. There are two ways of doing this.

1) For small adjustments to an existing built-in-view simply subclass the built-in-view and override its methods

2) You can create your own View subclass

→ If you choose to create your own View subclass, you can following advantages

a) You get control over the appearance and function of a screen element (custom view)

b) You can create a volume control knob-type custom view using Android 2D graphics.

c) You can combine 2-3 different built-in-controls and make a compound complex custom view.

There is an example in the Android Demo API's (Notepad Tutorial). The example overrides EditText Button to create Notepad lined page effect.

d) You can capture key presses and handle them in some custom way.


High Level-Basic Approach (If you are extending a Built-in View)

1) Extend an existing View (Built-in View). Sublass it with your own class

2) Override methods from the superclass that start with “on”.


a) onDraw()

b) onMeasure()

c) onKeyDown() , onKeyUp(), onTouch() … and so on


3. Use your new Views in your Activity

→ setContentView (View v)

→ < view class = viewclass >

→ < view class = < parentclass > $ < viewclass > >

For fully customized View

1) You have to extend View class.
2) Implement constructor myView(attributes, parameters)
3) Implement event listeners
4) Override methods from the superclass that start with “on”.

a) onDraw()

b) onMeasure()

5) Use your new Views in your Activity

→ setContentView (View v)

→ < view class = viewclass >

→ < view class = < parentclass > $ < viewclass > >

P.S. Sample Code (Eclipse Project) can be downloaded from here.