I create a class "Properties":
class Properties {
var x = 200f
}
In the second class "Canvas" I can change the variable "p.x" and the Canvas shows the correct Coordinates on myCanvas.drawCircle(p.x, 100, 10f, myPaint):
val p = Properties()
class Canvas(context: Context?, attrs: AttributeSet) : View(context, attrs) {
...
p.x = 600f
override fun onDraw(myCanvas : Canvas) {
myCanvas.drawCircle(p.x, 100, 10f, myPaint)
}
}
But if I try to change the p.x in MainActivity.kt nothing happens in the Canvas (the value p.x will be changed correctly)
lateinit var getCanvasClassID : View
val p = Properties()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
getCanvasClassID = findViewById(R.id.canvasView)
p.x = 700f
getCanvasClassID.invalidate()
}
2
Answers
I think these are totally different Properties objects in your classes.
You need to make sure that the
Canvas
class is aware of the changes to theProperties
object made inMainActivity
. Currently, theCanvas
class uses a separate instance ofProperties
, so changes made inMainActivity
do not reflect in theCanvas
class.One way to achieve this is by passing the same
Properties
instance to theCanvas
class and using it within theonDraw
method.In the caller side you can used it like this: