一、前言
有差不多一个星期没有更新过博客,昨天是周末,通过学习《Android群英传》一书,了解了一下自定义View、TextView的知识,并动手写了自定义TextView的demo,今天正好记录下来,即可以复习昨天所学,也可以分享给大家。
二、实现自定义TextView
通过学习,实现了两种样式的TextView的自定义:
- 自定义TextView背景(基础)
- 自定义TextView文本闪烁
我刚接触自定义View,起步要求不高,所以实现上面的两个效果只是重写了TextView的onDraw()方法。
1. 自定义TextView背景(基础)
实现代码,注释很详细,这里就不再赘述了。
public class CustomTextViewBg extends TextView
{
private Paint mPaint1, mPaint2;
private Canvas canvas;
public CustomTextViewBg(Context context)
{
super(context);
}
public CustomTextViewBg(Context context, AttributeSet attrs)
{
super(context, attrs);
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 = new Canvas();
}
/**
* 修改TextView需要重写onDraw()
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas)
{
//绘制外层矩形
canvas.drawRect(
0,
0,
getMeasuredWidth(),
getMeasuredHeight(),
mPaint1);
//绘制内层矩形
canvas.drawRect(
10,
10,
getMeasuredWidth() - 10,
getMeasuredHeight() - 10,
mPaint2);
canvas.save();
//绘制文字前平移10像素
canvas.translate(10, 0);
//在回调父类方法前,实现自己的逻辑,对TextView来说即是在绘制文本内容前
//父类完成的方法,即绘制文本
super.onDraw(canvas);
//在回调父类方法后,实现自己的逻辑,对TextView来说即是在绘制文本内容后
canvas.restore();
}
}
实现效果图:
2. 自定义TextView文本闪烁
public class CustomTextViewGlint extends TextView
{
private int mViewWidth;
private Paint mPaint;
private LinearGradient mLinearGradient;
private Matrix mGradientMatrix;
private int mTranslate;
public CustomTextViewGlint(Context context)
{
super(context);
}
/**
* 自定义TextView,一定要有这个构造方法
* @param context
* @param attrs
*/
public CustomTextViewGlint(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
if (mViewWidth == 0){
mViewWidth = getMeasuredWidth();
if (mViewWidth > 0){
mPaint = getPaint();
mLinearGradient = new LinearGradient(
0,
0,
mViewWidth,
0,
new int[]{ Color.BLUE, 0xffffffff,Color.BLUE },
null, Shader.TileMode.CLAMP
);
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (mGradientMatrix != null){
mTranslate += mViewWidth/5;
if (mTranslate > 2*mViewWidth){
mTranslate = -mViewWidth;
}
mGradientMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
postInvalidateDelayed(100);
}
}
}
注:在继承TextView后,选择构造方法的时候,必须要选择带两个参数的构造方法,因为默认的布局文件调用的是这个构造方法,否则会导致项目运行时崩溃。
3. 实现效果图

三、结束
希望朋友们能喜欢,有什么建议都可以给我留言。
网友评论