In this section, we will explore how to create custom views and use the Canvas class in Android. Custom views allow you to create unique UI components that are not available in the standard Android UI toolkit. The Canvas class provides a powerful way to draw shapes, text, and images directly onto the screen.
Key Concepts
- Custom Views: Creating your own view by extending the
Viewclass. - Canvas: A class that provides methods for drawing on a bitmap.
- Paint: A class that holds the style and color information about how to draw geometries, text, and bitmaps.
- Drawing Shapes: Using Canvas methods to draw shapes like circles, rectangles, and lines.
- Handling Touch Events: Making your custom view interactive by handling touch events.
Creating a Custom View
To create a custom view, you need to extend the View class and override its onDraw method. Here is a simple example:
// MyCustomView.java
package com.example.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyCustomView extends View {
private Paint paint;
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw a red circle at the center of the view
int width = getWidth();
int height = getHeight();
int radius = Math.min(width, height) / 4;
canvas.drawCircle(width / 2, height / 2, radius, paint);
}
}Explanation
- Constructor: The constructor initializes the
Paintobject, which defines the color and style of the drawing. - onDraw Method: The
onDrawmethod is where you perform all your drawing. In this example, we draw a red circle at the center of the view.
Using the Custom View in XML
To use the custom view in your layout, you need to add it to an XML layout file:
<!-- activity_main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.customview.MyCustomView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>Drawing Shapes with Canvas
The Canvas class provides several methods for drawing shapes:
drawCircle(float cx, float cy, float radius, Paint paint)drawRect(float left, float top, float right, float bottom, Paint paint)drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
Here is an example of drawing multiple shapes:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw a red circle
paint.setColor(Color.RED);
canvas.drawCircle(100, 100, 50, paint);
// Draw a blue rectangle
paint.setColor(Color.BLUE);
canvas.drawRect(200, 200, 400, 400, paint);
// Draw a green line
paint.setColor(Color.GREEN);
canvas.drawLine(500, 500, 700, 700, paint);
}Handling Touch Events
To make your custom view interactive, you can override the onTouchEvent method:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Handle touch down event
return true;
case MotionEvent.ACTION_MOVE:
// Handle touch move event
return true;
case MotionEvent.ACTION_UP:
// Handle touch up event
return true;
}
return super.onTouchEvent(event);
}Practical Exercise
Task
Create a custom view that draws a smiley face. The face should be a yellow circle, with two black eyes and a black smile.
Solution
// SmileyView.java
package com.example.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class SmileyView extends View {
private Paint paint;
public SmileyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw face
paint.setColor(Color.YELLOW);
canvas.drawCircle(300, 300, 200, paint);
// Draw eyes
paint.setColor(Color.BLACK);
canvas.drawCircle(220, 250, 20, paint);
canvas.drawCircle(380, 250, 20, paint);
// Draw mouth
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
canvas.drawArc(200, 200, 400, 400, 0, 180, false, paint);
}
}Explanation
- Face: Drawn using a yellow circle.
- Eyes: Drawn using two smaller black circles.
- Mouth: Drawn using an arc.
Summary
In this section, you learned how to create custom views and use the Canvas class to draw shapes, text, and images. You also learned how to handle touch events to make your custom views interactive. Custom views and Canvas provide a powerful way to create unique and engaging UI components in your Android applications.
Android Studio Course
Module 1: Introduction to Android Studio
- Introduction to Android Studio
- Setting Up Android Studio
- Understanding the Android Studio Interface
- Creating Your First Android Project
Module 2: Basic Android Development
- Understanding Android Project Structure
- Introduction to XML Layouts
- Basic UI Components
- Introduction to Activities
- Running Your App on an Emulator
Module 3: Intermediate Android Development
- Introduction to Intents
- Working with Fragments
- Handling User Input
- Using RecyclerView
- Networking in Android
Module 4: Advanced Android Development
- Data Persistence with SQLite
- Using Room for Database Management
- Advanced UI Components
- Custom Views and Canvas
- Working with Background Tasks
Module 5: Professional Android Development
- Implementing MVVM Architecture
- Dependency Injection with Dagger
- Unit Testing and UI Testing
- Publishing Your App on Google Play
- Performance Optimization
