Android 给view加红色数字提醒角标

在 Android 应用中,经常会有一些需要提醒用户的未读消息数、未处理事项数等需求,这时我们可以在视图的角落添加一个红色数字提醒角标。
实现这一功能的核心是在视图上添加一个小红点,然后在红点上绘制数字。下面是一个示例代码:
```
public class BadgeView extends View {
private Paint mPaint;
private int mCount;
public BadgeView(Context context) {
super(context);
init();
}
public BadgeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(true);
mPaint.setTextSize(30);
}
public void setCount(int count) {
mCount = count;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int radius = width / 2;
canvas.drawCircle(radius, radius, radius, mPaint);
if (mCount > 0) {
String text = String.valueOf(mCount);
float textWidth = mPaint.measureText(text);
float textHeight = mPaint.descent() - mPaint.ascent();
float x = radius - textWidth / 2;
float y = radius - textHeight / 2 - mPaint.ascent();
canvas.drawText(text, x, y, mPaint);
}
}
}
```
以上代码定义了一个名为 BadgeView 的自定义 View,它继承自 View 类。在构造函数中初始化画笔,并在 onDraw 方法中绘制红色圆点和数字。
我们可以在布局文件中使用 BadgeView,例如:
```
android:id="@+id/badge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:padding="5dp" android:background="@drawable/circle" android:textColor="#FFFFFF" android:textSize="20sp" android:gravity="center"/> ``` 使用时,可以通过 setCount 方法设置数字: ``` BadgeView badgeView = findViewById(R.id.badge); badgeView.setCount(10); ``` 以上就是 Android 给 view 加红色数字提醒角标的实现方法,可以方便地提醒用户未读消息数、未处理事项数等。