Android Simple Custom View

android-custom-viewAndroid SDK has a large set of standard views such as Button, TextView and ImageView. However, the framework also enables developers to create custom views that meet unique needs for example a pie chart or donut chart. This post is aiming to show you how to create a new simple custom view, how to draw the shape of the view and how to give it a nice look and feel.

Objectives:

  • How to create a new custom view?
  • How to define custom views attributes?
  • How draw on canvas?
  • How to give your view artistic effects?

( 1 ) Create a new Android project

  • Application Name: Simple Custom View
  • Project Name: android-custom-view
  • Package Name: com.hmkcode.views

( 2 ) Create Custom View

First step in creating a custom view is to extend base class “View“. Also, you must override at least one of the three overloaded constructors. Here we will override the 2-parameter constructor where the first parameter is the context and the second is the set of parameters that will be passed when creating the view in layout XML file.

  • /com/hmkcode/views/SimpleView.java
public class SimpleView extends View {

	public SimpleView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

}

( 3 ) Defining Custom View Attributes

When we add a view to the layout file, we usually set some attribute values such as width, height and so on. If your view has special attribute then you can define custom attributes.

Attributes can be in different format such enum, boolean, float, integer, string…etc.

  • Create a new xml file attrs.xml under /res/values
  • We will define two attributes, first shape attribute of type enum and the second is dim of type dimension.
  • /res/values/attrs.xml
<resources>
    <declare-styleable name="FaceView">
        <attr name="shape" format="enum">
            <enum name="circle" value="0"/>
            <enum name="square" value="1"/>
        </attr>
        <attr name="dim" format="dimension"/>
    </declare-styleable>
</resources>

( 4 ) Adding your Custom View to Layout

After extending View class and defining custom attributes (if needed), you can use the custom view in layout XML files just like other standard views. However, if your view has custom attributes, then you need to define a namespace that your attributes belong to. Custom attribute belong to http://schemas.android.com/apk/res/[your package name].

  • Here we will two SimpleView one with shape=”circle” and the other with shape=”square”
  • /res/layout/activity_main.xml
<LinearLayout 
     ....
    xmlns:customviews="http://schemas.android.com/apk/res/com.hmkcode.views"
    ....
    android:orientation="vertical"
    >

    <com.hmkcode.views.SimpleView
            android:id="@+id/simpleViewCircle"
            android:layout_width="140dp"
            android:layout_height="150dp"
            customviews:shape="circle"
            customviews:dim="70dp"
            android:layout_gravity="center_horizontal"
         />
    
     <com.hmkcode.views.SimpleView
            android:id="@+id/simpleViewSquare"
            android:layout_width="140dp"
            android:layout_height="140dp"
            customviews:shape="square"
            customviews:dim="140dp"
            android:layout_gravity="center_horizontal"
         />

     <TextView 
         android:id="@+id/tv"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center_horizontal"
         />
</LinearLayout>

( 5 ) Passing Custom Attributes Values to Custom View Class

Now we the custom view class is not yet aware of the custom attributes “shape and dim”. We need to pass them to the class to use them.

  • src/com/hmkcode/views/SimpleView.java
public class SimpleView extends View {

	float dim;
	int shape;

	public SimpleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.SimpleView,
                0, 0
        );
		
		try {
            dim = a.getDimension(R.styleable.SimpleView_dim, 20f);
            shape = a.getInteger(R.styleable.SimpleView_shape, 0);
        } finally {
            a.recycle();
        }
		
		
	}
...
}

( 6 ) Run & Test

Now at this step you can run the application, however nothing will show up on the screen because our new custom view is still blank or has NO “face” yet. Next we will draw some shape on the canvas so we can see it on the screen.

( 7 ) Draw on Custom View Canvas

  • To draw the custom view shape you need to override onDraw(Canvas) method of the custom view class. All the drawing shall be on the canvas object passed in the onDraw(Canvas) parameter.
  • Our simple custom view will draw a circle or a square based on the “shape” parameter.
  • To draw a circle use Canvas.drawCircle() which takes the x & y of the center of the circle and radius of the circle.
  • To draw a square use Canvas.drawRect() which takes x&y of the top-left and bottom-right corners of the rectangle.
  • Paint object defines the look and feel of the shape suhc as color.

 

  • src/com/hmkcode/views/SimpleView.java
package com.hmkcode.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class SimpleView extends View {

	float dim;
	int shape;
	Paint paint;
	
	public static final int CIRCLE = 0;
	public static final int SQUARE = 1;
	public SimpleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		....
        }
		
		paint = new Paint();
		paint.setColor(0xfffed325); // yellow 
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		switch(shape){
			case CIRCLE:
				canvas.drawCircle(dim, dim, dim, paint);
				break;
			case SQUARE:
				canvas.drawRect(0, 0, dim, dim, paint);
				break;
		}
	}
}

( 8 ) Add Click Listener to Custom View

Like other standard views you can add click listener to your custom views. Here we will add a click listener that displays “Circle” when clicking on circle and and “Square” when clicking on square.

  • scr/com/hmkcode/views/MainActivity.java
package com.hmkcode.views;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class MainActivity extends Activity implements OnClickListener {

	SimpleView svCircle;
	SimpleView svSquare;
	TextView tv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		svCircle = (SimpleView) findViewById(R.id.simpleViewCircle);
		svSquare = (SimpleView) findViewById(R.id.simpleViewSquare);
		tv = (TextView) findViewById(R.id.tv);
		
		svCircle.setOnClickListener(this);
		svSquare.setOnClickListener(this);

	}


	@Override
	public void onClick(View view) {
	
		switch(view.getId()){
			case R.id.simpleViewCircle:
				tv.setText("Circle");
				break;
			case R.id.simpleViewSquare:
				tv.setText("Square");
				break;
			
		}
		
	}
	
}

( 9 ) Run & Test

Now if you run the application this time you should be able to see a circle and a square.

android-custom-view

Source Code @ GitHub

Leave a Reply