实现原理是在TextView的基础上用画笔画出“已签到”效果。
首先我们要自定义一个TextView叫TextViewForCheck,代码如下:
package com.andan.view;
import com.andan.shouyoujun.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TextViewForCheck extends TextView {
private Paint paint=new Paint();
private Canvas canvas=new Canvas();
private boolean isCheck;
public TextViewForCheck(Context context, AttributeSet attrs) {
super(context, attrs);
isCheck = attrs.getAttributeBooleanValue(null, "isCheck", false);//获取自定义属性isCheck
}
public TextViewForCheck(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public TextViewForCheck(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(isCheck){
paint.setColor(getResources().getColor(R.color.arc_blue));
paint.setStrokeWidth(50);
paint.setTextSize(40);
paint.setFakeBoldText(true);//设置粗体效果
paint.setTextSkewX(1);//字体斜体
Rect rect =new Rect();
paint.getTextBounds("已签到", 0, 3, rect);
canvas.drawText("已签到", getWidth()/2-rect.width()/2, getHeight()/2+rect.height()/2, paint);
}
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
postInvalidate();//设置完成后重新绘制
}
}
然后在xml文件中引用该控件:
<com.andan.view.TextViewForCheck
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="星期一"
android:textSize="@dimen/NORMALSIZE"
isCheck="false"
/>
然后通过setCheck()来动态显示是否已经签到。
TextViewForCheck.setCheck(false);
TextViewForCheck.setCheck(true);