自定义view实现未读消息提示(小红点)

转载:http://blog.csdn.net/qq_28268507/article/details/70314844

自定义view继承RadioButton

public class NotifyRadioButton extends RadioButton {

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float radius;
boolean notify;

public NotifyRadioButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint.setColor(Color.RED);
    radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 12.0f, context.getResources().getDisplayMetrics());
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (notify) {
      //获取到DrawableTop,  0 drawableleft 1 drawabletop 2 drawableright 3 drawablebottom
        Drawable drawable = getCompoundDrawables()[1];
         //获取到Drawable的left right top bottom的值
        Rect bounds = drawable.getBounds();
        //float cx, float cy, float radius, @NonNull Paint paint
        float cx = getMeasuredWidth() / 2 + bounds.width() / 2 - radius / 2;
        float cy = getPaddingTop() + bounds.height() / 4;
        canvas.drawCircle(cx, cy, radius, paint);
    }
}

/**
 * 新消息提醒
 *
 * @param notify
 */
public void notify(boolean notify) {
    this.notify = notify;
    invalidate();
}

}

在代码中,通过id找到控件,调用notify(true),就可看到小红点的显示

你可能感兴趣的:(android)