3.5 自定义View
直奔主题,在View中通常有以下一些比较重要的回调方法:
- onFinishInflate():从XML加载组件后回调;
- onSizeChanged():组建大小改变时回调;
- onMeasure():回调该方法来进行测量;
- onLayout():回调该方法来确定显示的位置;
- onTouchEvent():监听到触摸事件时回调;
自定义View时只需要在特定的条件下回掉特定的方法即可。
通常情况下,有以下三种方法来实现自定义控件:
- 对现有的控件进行拓展;
- 通过组合控件实现新的控件;
- 重写View来实现全新的控件;
3.5.1 对现有的控件进行拓展
图中Hello World所呈现的TextView,
首先要继承已有的TextView控件,这样才能用得到绘制文本的作用,然后重写onDraw()的方法,
代码如下
@Override
protected void onDraw(Canvas canvas) {
//两种画笔
mpaint1=new Paint();
mpaint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
mpaint1.setStyle(Paint.Style.FILL);
mpaint2=new Paint();
mpaint2.setColor(Color.YELLOW);
mpaint2.setStyle(Paint.Style.FILL);
//绘制外层矩形
canvas.drawRect(0,0,getMeasuredWidthAndState(),getMeasuredHeightAndState(),mpaint1);
//绘制内层矩形
canvas.drawRect(10,10,getMeasuredWidthAndState()-10,getMeasuredHeightAndState()-10,mpaint2);
canvas.save();
//绘制文字前平移10
canvas.translate(10,0);
super.onDraw(canvas);
canvas.restore();
}
}
这样就能实现一个对TextView的拓展。