Android kotlin 自定义圆形数字提示好点 兼容1到99+不变形 详细代码
以下是一个使用Kotlin编写的自定义圆形数字提示的示例代码,该代码可以兼容1到99+的数字,并保持圆形不变形。
首先,创建一个名为CircleBadgeView的自定义View类:
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
class CircleBadgeView(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var text = ""
private val textBounds = Rect()
init {
paint.color = Color.RED
paint.style = Paint.Style.FILL
paint.textSize = resources.getDimensionPixelSize(R.dimen.circle_badge_text_size).toFloat()
paint.textAlign = Paint.Align.CENTER
}
fun setCount(count: Int) {
text = if (count > 99) "99+" else count.toString()
invalidate()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val desiredWidth = MeasureSpec.getSize(widthMeasureSpec)
val desiredHeight = MeasureSpec.getSize(heightMeasureSpec)
val textHeight = paint.descent() - paint.ascent()
val width = Math.max(desiredWidth, suggestedMinimumWidth) + paddingLeft + paddingRight
val height = Math.max(desiredHeight, suggestedMinimumHeight) + paddingTop + paddingBottom + textHeight.toInt()
setMeasuredDimension(width, height)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val radius = Math.min(width, height) / 2f
canvas.drawCircle(width / 2f, height / 2f, radius, paint)
paint.color = Color.WHITE
paint.getTextBounds(text, 0, text.length, textBounds)
val x = width / 2f
val y = height / 2f + (textBounds.bottom - textBounds.top) / 2f - textBounds.bottom
canvas.drawText(text, x, y, paint)
}
}
在上述代码中,我们定义了一个CircleBadgeView类,该类继承自View,并重写了onMeasure和onDraw方法。onMeasure方法用于计算View的宽度和高度,以确保View能够容纳文本和绘制的圆形背景。onDraw方法用于绘制圆形背景和文本。
接下来,在布局文件中使用CircleBadgeView:
<com.example.CircleBadgeView
android:id="@+id/badgeView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:textColor="#FFFFFF"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
最后,在Activity中设置圆形数字提示的数值:
val badgeView: CircleBadgeView = findViewById(R.id.badgeView)
badgeView.setCount(99) // 设置提示数值为99
这样,就可以在布局中显示一个带有圆形背景的数字提示,并且可以根据需要设置不同的数值
原文地址: https://www.cveoy.top/t/topic/iF4p 著作权归作者所有。请勿转载和采集!