'Is there a way to draw on a view canvas without extending it? (Android)

I need to draw simple shapes into a ViewGroup, like a rectangle or a line, and Canvas has the methods to it. When i extend the View class and override the onDraw method it works fine, but how can i achieve the same results by simply instantiating the view using xml? What i tried so far:

 val root = findViewById<ConstraintLayout>(R.id.root)
 val canvas = Canvas()
 canvas.drawRect(100f,100f,150f,150f,Paint().apply { this. color = Color.BLACK })

 root.draw(canvas)

But it doesn't work.



Solution 1:[1]

You don't. That's not something you can do in xml. Xml is meant for displaying predefined views. View classes define the drawing of those views. Now what you can do is put one view on top of another- for example a text view on top of an image view. That can get around the need to make a view class just to call drawText.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabe Sechan