先说下我的需求,我的页面上有个TextView,现在我想在文本边上显示一个有新消息的提示,类似下图:
这个可以通过TextView的 tv.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); 方法实现,问题是这个小Drawable怎么实现,自己也查阅了一些资料,没有我需要的,只好自己研究。还好弄出来了,现在把demo代码贴下,demo中是用ImageView显示的
iv = (ImageView)this.findViewById(R.id.iv);
btn = (Button)this.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
iv.setImageDrawable(new MyShapeDrawable(11));
}
});
public static class MyShapeDrawable extends ShapeDrawable{
private Paint mPaint;
private RectF rectF;
private String num;
private float textSize;
public MyShapeDrawable(int num) {
// TODO Auto-generated constructor stub
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
textSize = 22;
this.num = String.valueOf(num);
setIntrinsicWidth(40);
setIntrinsicHeight(40);
rectF = new RectF(0, 0, 40, 40);
}
@Override
public void draw(Canvas canvas) {
// TODO Auto-generated method stub
mPaint.setColor(Color.RED);
canvas.drawOval(rectF, mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(textSize);
float txtWidth = mPaint.measureText(num);
float x = (rectF.right - txtWidth)/2; // 计算文字水平位置
float y = (rectF.height() - textSize)/2 + textSize; // 计算文字垂直位置
canvas.drawText(num, x, y, mPaint);
}
}
另外附上Demo,有需要的同学自己下吧。