public class CounterView extends View implements View.OnClickListener {
private Paint mPaint;
private Rect rect;
private int mCount = 0;
public CounterView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
rect = new Rect();
setOnClickListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(Color.GRAY);
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
String text = String.valueOf(mCount);
mPaint.setColor(Color.YELLOW);
mPaint.setTextSize(50);
mPaint.getTextBounds(text,0,text.length(),rect);
int width = rect.width();
int height = rect.height();
canvas.drawText(text,getWidth()/2 - width/2,getHeight()/2 - height/2,mPaint);
}
@Override
public void onClick(View v) {
mCount++;
invalidate();
}
}