自定义消息提示控件
2018-05-18 本文已影响28人
Android师哥
night_rain.png
GitHub主页
开发中经常会用到消息提示这个功能,就像
消息提示.png
这样的效果,这里先简单做一个Demo看看效果,之后会在我的工具库中做更多的兼容和优化,然后发布!
首先老规矩
private int measureWidth;
private int measureHieght;
private float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics());
private TextPaint mTextPaint;
private String testContent = "99+";
private Paint mBackground;
private Rect mRect;
private int textWidht;
private int textHeight;
private String content = "";
public class CustomTextVew extends AppCompatTextView {
public CustomTextVew(Context context) {
this(context, null);
}
public CustomTextVew(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextVew(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//初始化画笔
initPaint();
//初始化尺寸(文字)
initSize();
}
}
重写onMeasure(测量控件尺寸)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureWidth = MeasureSpec.getSize(widthMeasureSpec);
measureHieght = MeasureSpec.getSize(heightMeasureSpec);
}
初始化画笔
private void initPaint() {
//文字画笔
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(textSize);
//文字居中
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setColor(Color.WHITE);
//背景画笔
mBackground = new Paint();
mBackground.setColor(Color.RED);
mBackground.setAntiAlias(true);
//绘制实心
mBackground.setStyle(Paint.Style.FILL);
}
初始化文字尺寸
//这里默认使用"99+"字符的尺寸
mRect = new Rect();
mTextPaint.getTextBounds(testContent, 0, testContent.length(), mRect);
//文字最大的宽
textWidht = mRect.width();
//文字的高
textHeight = mRect.height();
重要的绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!TextUtils.isEmpty(content)) {
//需要绘制背景的尺寸(默认在最大尺寸的基础了左右在加2dp的空间)
float size = textWidht + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
//绘制背景
canvas.drawCircle(measureWidth - size / 2, size / 2, size / 2, mBackground);
//绘制文字
canvas.drawText(content, measureWidth - size / 2, size / 2 + textHeight / 2, mTextPaint);
}
}
最后暴露一个方法,方便设置值
/**
* 设置提示数字
*
* @param hint
*/
public void setHintText(String hint) {
this.content = hint;
//重绘
invalidate();
}
效果
效果图.pngGitHub主页