下面通过自定义的View创建了一个同心圆的视图:
com.mxd.view.BullsEyeView.java
public class BullsEyeView extends View { private Paint mPaint; private Point mCenter; private float mRadius; /** * Java构造函数 */ public BullsEyeView(Context context) { this(context, null); } /** * XML构造函数 */ public BullsEyeView(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** * 带有样式的XML构造函数 */ public BullsEyeView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 创建用于绘制视图的画笔 mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 画笔的样式 mPaint.setStyle(Style.FILL); // 圆心 mCenter = new Point(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width, height; // 内容的大小 int contentWidth = 100; int contentHeight = 100; width = getMeasurement(widthMeasureSpec, contentWidth); height = getMeasurement(heightMeasureSpec, contentHeight); setMeasuredDimension(width, height); } /** * 用于测量宽度和高度 */ private int getMeasurement(int measureSpec, int contentSize) { int specSize = MeasureSpec.getSize(measureSpec); switch(MeasureSpec.getMode(measureSpec)) { case MeasureSpec.AT_MOST: return Math.min(specSize, contentSize); case MeasureSpec.UNSPECIFIED: return contentSize; case MeasureSpec.EXACTLY: return specSize; default: return 0; } } @Override protected void onSizeChanged(int w, int h, int lodw, int oldh) { if(w != oldh || h != lodh) { // 有参数变化,则复位参数 mCenter.x = w / 2; mCenter.y = h / 2; mRadius = Math.min(mCenter.x, mCenter.y); } } @Override protected void onDraw(Canvas canvas) { // 绘制一系列从大到小的同心圆 mPaint.setColor(Color.RED); canvas.drawCircle(mCenter.x, mCenter.y mRadius, mPaint); mPaint.setColor(Color.WHITE); canvas.drawCircle(mCenter.x, mCenter.y, mRadius * 0.7, mPaint); mPaint.setColor(Color.GREEN); canvas.drawCircle(mCenter.x, mCenter.y, mRadius*0.5, mPaint); mPaint.setColor(Color.WHITE); canvas.drawCircle(mCenter.x, mCenter.y, mRadius*0.3, mPaint); } }
三个构造函数:
View(Context context) :通过java代码来创建视图
View(Context context, AttributeSet attrs):从XML文件中创建视图,AttributeSet包括xml中加载到View上的所有属性
View(Context context, AttributeSet attrs, int delStyle)
在xml文件中使用自定义控件:
<com.mxd.view.BullsEyeView android:layout_width="match_parent" android:layout_height="wrap_content" />