Instantiating a custom view in Android

Creating a custom view/control in Android is fairly simple – here are the steps I used:

  1. Create a new class which extends from the ‘View’ abstract base class. E.g.
    public class MyCustomControl extends View
  2. Provide constructor overloads for ALL of the following prototypes, where initView() is a method in which you perform initialization of things such as Paint objects:
    public MyCustomControl(Context context)
    	{
    		super(context);
    		initView();
    	}
    	
    	public MyCustomControl(Context context, AttributeSet attrs)
    	{
    		super(context, attrs);
    		initView();
    	}
    
    	public MyCustomControl(Context context, AttributeSet attrs, int defStyle)
    	{
    		super(context, attrs, defStyle);
    		initView();
    	}
    
  3. Override onMeasure() in order to scale your control to the parent drawing area, such as shown in this good example.
  4. Do your canvas drawing operations in onDraw on the supplied Canvas object.
  5. Instantiate your custom view in a layout xml file (e.g. main.xml), for example:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    	<com.android.samples.MyCustomControl
    		android:id="@+id/myCustomControl"
        	android:layout_width="fill_parent" 
        	android:layout_height="fill_parent" 
        />
    </LinearLayout>

I found that if I didn’t add the 2nd and 3rd constructors, I got an exception when calling setContentView(R.layout.main) from onCreate() of the main Activity. You can instead construct an instance of the view manually in onCreate() of the main Activity, and then call setContentView(yourCustomViewInstance) if you don’t want to use XML layout.

4 thoughts on “Instantiating a custom view in Android

Comments are closed.