5

I'm trying to use a SurfaceView in Android to hold a Camera preview. The documentation tells me that I need to call startPreview in the surfaceCreated callback for the surface holder. I'm trying to set the callback like so

this.surface!!.holder!!.addCallback(SurfaceHolder.Callback() {
    fun surfaceChanged(holder: SurfaceHolder, format: Int, 
                       width: Int, height: Int) {

    }

    fun surfaceCreated(holder: SurfaceHolder) {

    }

    fun surfaceDestroyed(holder: SurfaceHolder) {

    }
})

However, I get the error:

SurfaceHolder.Callback has no constructors.

I'm confused why this doesn't work when something like this does:

Thread(Runnable() {
    fun run() {
        ...        
    }
})
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
robz
  • 89
  • 1
  • 8
  • 1
    Your second case is wrong as well, you are not actually overriding the `run()` method in Runnable but passing in a lambda that contains a nested `run()` function that is never called. Both examples are invalid. – Jayson Minard Jun 02 '17 at 22:43
  • Also for the run example for Runnable, you don't need to specify the interface either and can just use SAM conversion and pass in a lambda `Thread { ... }` – Jayson Minard Jun 02 '17 at 22:46

1 Answers1

10

To create an object of an anonymous subclass you need to use the object: expression:

this.surface!!.holder!!.addCallback(object: SurfaceHolder.Callback {
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, 
                                width: Int, height: Int) {
        ...        
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        ...
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        ... 
    }
})

and don't forget to use the override keyword per overridden method as well ;)

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85