当我们不满足于Android提供的原生控件和布局时,就应该考虑到自定义view。
自定义View分类:
- 继承View或者ViewGroup类。
- 自定义组合控件,即将几种控件组合起来形成一个新的控件。
- 自定义扩展控件,也就是继承现有的控件,在该控件的基础之上添加新的功能。
自定义步骤为:
- 构造函数,View初始化。
- onMeasure,测量View大小。
- onSizeChanged,确定View大小。
- onLayout,确定子View布局。
- onDraw,实际绘制内容
- 提供接口,控制View或监听View某些状态。
示例:画一个五角星,代码如下:
public class StarView extends View {
private Paint redPaint; //红色画笔
public StarView(Context context) {
super(context);
initPaint();
}
public StarView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public StarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 初始化画笔函数
*/
private void initPaint() {
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setStyle(Paint.Style.FILL);
redPaint.setColor(Color.RED);
}
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth(); //画布宽度
int height = getHeight(); //画布高度
canvas.translate(width/2, height/2); // 移动坐标原点到画布中心
for (int i=0; i<5; i++){ // 绘制2条线,然后翻转
canvas.drawLine(-80,-100,0,-350,redPaint);
canvas.drawLine(0,-350,80,-100,redPaint);
canvas.rotate(72);
}
}
}

网友评论