public class MyView extends View implements View.OnClickListener{
int[] colors = new int[]{
Color.RED,Color.YELLOW,Color.GREEN
};
int[] colores = new int[]{
Color.BLUE,Color.BLACK,Color.WHITE
};
//背景色
private int bgColor;
//文字色
private int textColor;
//文字大小
private int textSize;
private Paint paint;
private Rect r;
private String str = "4232";
public MyView(Context context) {
this(context,null);
}
public MyView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyViewAttrs,defStyleAttr,0);
bgColor = ta.getColor(R.styleable.MyViewAttrs_bgColor, Color.BLACK);
textColor = ta.getColor(R.styleable.MyViewAttrs_textColor,Color.WHITE);
textSize = ta.getDimensionPixelSize(R.styleable.MyViewAttrs_textSize,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
30,getResources().getDisplayMetrics()));
ta.recycle();
setOnClickListener(this);
paint = new Paint();
r = new Rect();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if(widthMode == MeasureSpec.EXACTLY){ }else{ widthSize = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,200,getResources().getDisplayMetrics()); } if(heightMode == MeasureSpec.EXACTLY){ }else{ heightSize = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,100,getResources().getDisplayMetrics()); } setMeasuredDimension(widthSize,heightSize); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //绘制矩形区域 paint.setColor(bgColor); paint.setStrokeWidth(3); paint.setAntiAlias(true); canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint); //获取文字宽高,绘制文字 paint.setTextSize(textSize); paint.setColor(textColor); paint.getTextBounds(str,0,str.length(),r); canvas.drawText(str,getWidth()/2-r.width()/2,getHeight()/2+r.height()/2,paint); } //生成随机字符串 private String changeText(){ Random random = new Random(); String num = ""; for(int i = 0;i < 4;i++){ num = num + random.nextInt(10); } return num; } @Override public void onClick(View view) { str = changeText(); Random random = new Random(); int index = random.nextInt(3-1); bgColor = colors[index]; textColor=colores[index]; invalidate(); }
//自定义属性
<declare-styleable name="MyViewAttrs">
<attr name="bgColor" format="color">#dddddd</attr>
<attr name="textColor" format="color">#ff0000</attr>
<attr name="textSize" format="dimension">30</attr>
</declare-styleable>