自定义控件-消息个数提醒控件

来源:互联网 发布:英文字帖 知乎 编辑:程序博客网 时间:2024/05/24 15:37

前言

在QQ中有消息个数提醒的控件,虽然现在没用到,但是以后可能会用到,所以就实现它,也不难。

实现

效果图如下:

这里写图片描述

先贴源码了:

public class TipNumberView extends TextView {    private Paint mBgPaint ;    PaintFlagsDrawFilter pfd;     public TipNumberView(Context context, AttributeSet attrs) {        super(context, attrs);        //初始化画笔        mBgPaint = new Paint();        mBgPaint.setColor(Color.RED);        mBgPaint.setAntiAlias(true);        pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);     }    public TipNumberView(Context context) {        this(context,null);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        //得到测量的高度和宽度        int measuredWidth = getMeasuredWidth();        int measuredHeight = getMeasuredHeight();        int max = Math.max(measuredWidth, measuredHeight);        //设置控件区域大小        setMeasuredDimension(max, max);    }    //设置背景颜色    @Override    public void setBackgroundColor(int color){        mBgPaint.setColor(color);    }    /**     * 设置通知个数显示     * @param text     */    public void setNotifiText(int text){        setText(text+"");    }    public void setNotifiText(String text){        setText(text);    }    //绘图    @Override    public void draw(Canvas canvas) {        //设置绘图无锯齿        canvas.setDrawFilter(pfd);        canvas.drawCircle(getWidth()/2, getHeight()/2, Math.max(getWidth()/2, getHeight())/2, mBgPaint);        super.draw(canvas);    }}

我是直接继承至TextView,因为TextView有setText方法,所以只需要绘制圆形的红色背景,然后调用方法setText即可,这就是实现的思路。

先要覆盖onMeasure方法来得到宽度和高度,因为背景为圆形,所以我们取宽度和高度两者之间的最大值,然后设置控件大小为一个正方形,在这个正方形的矩形里面,调用drawCircle方法来绘制圆形,设置画笔的颜色为红色即可。

小结

在布局文件使用这个类的时候,要设置android:gravity为center,这样数字就可以居中了,之所以没有继承View来进行写,因为View还要自己去画数字,这样就增加了难度,不值得了。

【源码下载】

0 0