安卓自定义TextView实现签到效果

实现原理是在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);

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值