自定义控件之--继承控件(圆形TextView)

师从郭大,自学于心,继承控件无疑就是继承自现有控件,保持继承的控件的属性并进行必要的扩展。
 
比如下面这个自定义控件,它就保持了TextView的属性,并对TextView的外观进行必要的修改该来适应自己的项目,主要实现的是一个圆形的TextView的功能。
 
三个构造方法:
onMesure():onMeasure()方法顾名思义就是用于测量视图的大小的,确定视图的宽度和高度的规格和大小;
draw():视图绘制,canvas.drawCircle(getWidth()/2, getHeight()/2,Math.max(getWidth(), getHeight())/2, mBgPaint);绘制圆形
 
给Canvas加上抗锯齿标志:
PaintFlagsDrawFilter pfd =newPaintFlagsDrawFilter(0,Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
canvas.setDrawFilter(pfd);
 
绘制圆形的TextView:
canvas.drawCircle(getWidth()/2, getHeight()/2,Math.max(getWidth(), getHeight())/2, mBgPaint);
 
设置回调方法,然后控制组件的内容和背景:
 
setBackgroundColor
setNotifiText
  1.  1 package com.example.circletextview;
     2 import android.content.Context;
     3 import android.graphics.Canvas;
     4 import android.graphics.Color;
     5 import android.graphics.Paint;
     6 import android.graphics.PaintFlagsDrawFilter;
     7 import android.util.AttributeSet;
     8 import android.widget.TextView;
     9 public class CircleView extends TextView {
    10     private Paint mBgPaint = new Paint();
    11     PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); 
    12     public CircleView(Context context, AttributeSet attrs, int defStyle) {
    13         super(context, attrs, defStyle);
    14     }
    15     public CircleView(Context context, AttributeSet attrs) {
    16         super(context, attrs);
    17         mBgPaint.setColor(Color.WHITE);
    18         mBgPaint.setAntiAlias(true);
    19     }
    20     public CircleView(Context context) {
    21         super(context);
    22         mBgPaint.setColor(Color.WHITE);
    23         mBgPaint.setAntiAlias(true);
    24     }
    25     @Override
    26     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    27         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    28         int measuredWidth = getMeasuredWidth();
    29         int measuredHeight = getMeasuredHeight();
    30         int max = Math.max(measuredWidth, measuredHeight);
    31         setMeasuredDimension(max, max);
    32     }
    33     @Override
    34     public void setBackgroundColor(int color) {
    35         mBgPaint.setColor(color);
    36     }
    37     /**
    38      * 设置通知个数显示
    39      * @param text
    40      */
    41     public void setNotifiText(int text){
    42         setText(text+"");
    43     }
    44     @Override
    45     public void draw(Canvas canvas) {
    46         canvas.setDrawFilter(pfd);//给Canvas加上抗锯齿标志
    47         canvas.drawCircle(getWidth()/2, getHeight()/2, Math.max(getWidth(), getHeight())/2, mBgPaint);
    48         super.draw(canvas);
    49     }
    50 }
github:
https://github.com/soyoungboy/MyCircleTextView



posted @ 2015-06-20 18:35  西北野狼  阅读(2716)  评论(0编辑  收藏  举报