skip to Main Content

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


  1. I think these are totally different Properties objects in your classes.

    Login or Signup to reply.
  2. You need to make sure that the Canvas class is aware of the changes to the Properties object made in MainActivity. Currently, the Canvas class uses a separate instance of Properties, so changes made in MainActivity do not reflect in the Canvas class.

    One way to achieve this is by passing the same Properties instance to the Canvas class and using it within the onDraw method.

    class Canvas(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    
        var properties: Properties = Properties()
            set(value) {
                field = value
                invalidate()
            }
    
        override fun onDraw(myCanvas: android.graphics.Canvas) {
    
            myCanvas.drawCircle(properties.x, 100f, 10f, myPaint)
        }
    }
    

    In the caller side you can used it like this:

    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.properties = p
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search