How to extend the View class in Android to create a custom View

Android FAQ: How do I write a custom View class in Android? (Or, how do I extend a View class?)

I showed this code in my How to draw a rectangle in Android tutorial, but I thought I’d share it again here in the context of “How to extend the View class in Android.” In short, all you need to do is extend Android’s View class, implement the constructor of your custom class, and then put the desired behavior in the onDraw method, which you inherit and override from the base View:

package com.alvinalexander.viewdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

public class CustomView extends View {
    
    private Rect rectangle;
    private Paint paint;

    public CustomView(Context context) {
        super(context);
        int x = 50;
        int y = 50;
        int sideLength = 200;
        
        // create a rectangle that we'll draw later
        rectangle = new Rect(x, y, sideLength, sideLength);

        // create the Paint and set its color        
        paint = new Paint();
        paint.setColor(Color.GRAY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLUE);
        canvas.drawRect(rectangle, paint);
    }

}

Now that you have your CustomView, you just need to use it in the setContentView method your Activity:

package com.alvinalexander.view;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CustomView(this));
    }

}

In the case of this example, this will result in the following appearance when you run this Activity in the Android emulator:

In summary, if you wanted to see how to extend the View class in Android to create your own custom view, I hope this example is helpful.