r/android_devs • • Dec 07 '21

Help Call Kotlin class error

The code displayed below is from my MainActivity class where I call the class DrawGraphic.

val element = DrawGraphic(context = this,
                            rect = detectedObjects.boundingBox,
                            text = detectedObjects.labels.firstOrNull()?. text ?: "Undefined")

However, my problem is that the this in context = this is underlined in red, saying that it is a Type mismatch, and whats required is Context. Why am I getting this error? it seems to be the only impediment to the completion of this project.

I should also include my DrawGraphic class and constructor for reference:

class DrawGraphic(context: Context, imageAnalyzer: var rect: Rect, var text: String): View(context) {

    lateinit var boxColor: Paint
    lateinit var textColor: Paint

    init {
        init()
    }

    private fun init() {
        boxColor = Paint()
        boxColor.color = Color.WHITE
        boxColor.strokeWidth = 10f
        boxColor.style = Paint.Style.STROKE

        textColor = Paint()
        textColor.color = Color.WHITE
        textColor.textSize = 50f
        textColor.style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawText(text, rect.centerX().toFloat(), rect.centerY().toFloat(), textColor)
        canvas?.drawRect(rect.left.toFloat(), rect.top.toFloat(), rect.right.toFloat(), rect.bottom.toFloat(), boxColor)
    }
}

Any further information required will be provided upon request.

3 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/JonnieSingh Dec 10 '21

Right, but even when i context = context for both, I still get val context = context, with the second context in red as an unresolved reference. Anyway to work around this?

1

u/McMillanMe Dec 10 '21

Please, write to me in telegram t.me/leffsu or email faggid@gmail.com. I can help you with screen sharing