Search code examples
androidkotlintextview

Custom TextView text not visible


I have a simple custom TextView that adds background color with rounded corners. However, the text is not visible, as you can see from the green little square. I tried setting the text and textColor in XML file as well, same thing. Where did I do wrong?

enter image description here

class StatusRectView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {

    private var cornerRadius = 0.8f
    private val paint = Paint()
    private var size = 0  

    init {
        paint.isAntiAlias = true
        gravity = Gravity.CENTER
        setTextColor(Color.WHITE)
        text = "D"
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        size = Math.min(measuredWidth, measuredHeight)
        setMeasuredDimension(size, size)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        paint.color = Color.GREEN
        paint.style = Paint.Style.FILL

        val rectF = RectF(0f,  0f, size * 1f, size * 1f)
        canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint)
    }
}

Solution

  • You have to call super.onDraw after drawing the rectangle.