Android: How to build a custom View

Create a View Class

Any custom view class should be derived out of the base class "View" and should overwrite the callback function "onDraw". When this function is called by the android frame work it receives a handle to the "Canvas" object on which the required drawings can be performed. In our case we are drawing a rectangle and a Circle using this canvas object.

 

RectView.java

package com.tutorsground.android.customview;
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 RectView extends View {

    private Paint paint = new Paint();
    Rect rect = new Rect();

    public RectView(Context context) {
        super(context);

        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(10f);
        // (left <= right) && (top <= bottom)
        rect.left = 100;
        rect.right = 400;
        rect.top = 100;
        rect.bottom = 400;
    }

    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawRect(rect, paint);
        canvas.drawCircle(250, 250, 150, paint);
    }
}

Use the custom View class in your application

MainActivity.java 

package com.tutorsground.android.customview;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RectView rv = new RectView(this);
        setContentView(rv);
    }
}

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorsground.android.customview" >
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Results

Android custom view