相信android coder早就遇到过已有的控件满足不了工作流的情况,所以我们需要创建新的View.
创建新的View的方法与希望达到的目的有关:
(1)如果现有控件已经可以满足希望实现的功能,那么就只需要对现有控件的外观或动作经行扩展和修改即可
(2)通过组合多个控件来创建不可分割的,可重用的控件
(3)创建全新的控件
下面介绍第一种方法修改现有的控件,通过重写onDraw()方法来修改外观
(1)创建一个新的扩展了TextView的MyTextView ,它包含一个 onDraw()方法,以及init()方法的构造函数
public class MyTextView extends TextView{
public MyTextView(Context context) {
super(context);
init();
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
private void init(){
}
}
(2)创建资源文件
colors.xml:
<resources> <color name="notepad_paper">#AAFFFF99</color> <color name="notepad_lines">#FF0000FF</color> <color name="notepad_margin">#90FF0000</color> <color name="notepad_text">#AA0000FF</color> </resources>
dimens.xml:
<resources>
<dimen name="notepad_margin">30px</dimen>
</resources>
(3)通过资源文件创建外观
private Paint marginPaint;
private Paint linePaint;
private int paperColor;
private float margin;
private void init(){
Resources myResources = getResources();
//创建绘图刷
marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
marginPaint.setColor(myResources.getColor(R.color.notepad_margin));
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(myResources.getColor(R.color.notepad_lines));
paperColor = myResources.getColor(R.color.notepad_paper);
margin = myResources.getDimension(R.dimen.notepad_margin);
(4)绘制页面
protected void onDraw(Canvas canvas) {
//绘制页面颜色
canvas.drawColor(paperColor);
//绘制规则的直线
canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);
canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight(), linePaint);
//绘制边缘
canvas.drawLine(margin,0,margin,getMeasuredHeight(),marginPaint);
//移动文本,跨过边缘
canvas.save();
canvas.translate(margin, 0);
//使用TextView渲染文本
super.onDraw(canvas);
canvas.restore();
}
}
通过以上四个步骤,就完成了通过修改TextView来实现自己的View.