public class CircleView extends View { private Paint paint = new Paint(); public CircleView(Context context) { super(context); } public CircleView(Context context, AttributeSet attrs) { super(context, attrs); } public CircleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint); } }
public class LineChartView extends View { private Paint paint = new Paint(); private ListIn the above example, we extend the View class to create a custom LineChartView. We use onDraw() method to draw a line chart by connecting a series of data points. We use the Path object to create these lines and Canvas object to draw them. Package library: android.viewdataPoints = new ArrayList<>(); public LineChartView(Context context) { super(context); } public LineChartView(Context context, AttributeSet attrs) { super(context, attrs); } public LineChartView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setDataPoints(List dataPoints) { this.dataPoints = dataPoints; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setColor(Color.RED); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(4f); Path path = new Path(); for (int i = 0; i < dataPoints.size() - 1; i++) { PointF p1 = dataPoints.get(i); PointF p2 = dataPoints.get(i+1); path.moveTo(p1.x, p1.y); path.lineTo(p2.x, p2.y); } canvas.drawPath(path, paint); } }