自定义TextView计时器
本文是写在上篇自定义View Demo小例子之后的(代码都在链接里面)
思路
首先为画笔设置各种参数和监听事件,绘制控件宽高一致的矩形
`//抗锯齿的Style mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBounds = new Rect(); setOnClickListener(this);
`
绘制矩形 利用矩形测量文本的高宽参数 `
mPaint.setColor(Color.BLUE); canvas.drawRect(0,0,getWidth(),getHeight(),mPaint); mPaint.setColor(Color.YELLOW); mPaint.setTextSize(30); text = randomText(); mPaint.getTextBounds(text,0, text.length(),mBounds);//将字画在矩形里进行测量 float textWidth = mBounds.width(); float textHeight = mBounds.height(); canvas.drawText(text,getWidth()/2-textWidth/2,getHeight()/2+textHeight/2,mPaint);//基线`
最后绘制文本 注意drawText(,X,Y,)里面的y是基于基线的,所以要加上文本高度的一半.
重写onClick方法,让文本改变,再重绘
“`
@Override public void onClick(View v) {` text = randomText(); invalidate(); }
“`
最后附上randomText()方法
`private String randomText(){ Random rand = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size()<4){ int randomText = rand.nextInt(10);//0---9 set.add(randomText); } StringBuilder sb = new StringBuilder(); for(Integer i:set){ sb.append(""+i); } return sb.toString(); }
`
最后附上布局
`<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <custom.CounterView android:layout_width="100dp" android:layout_centerInParent="true" android:layout_height="100dp" /> </RelativeLayout>`