Embedding the interface anonymously in Kotlin results in a “no constructors” error

I am trying to use SurfaceView in Android to preview the camera. The documentation tells me that I need to call startPreview on the surfaceCreated callback for the surface holder. I am trying to set a callback like this

 
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 message:

SurfaceHolder.Callback has no constructors.

I am confused why this does not work when something like this:

Thread(Runnable() {
    fun run() {
        ...        
    }
})
+4
source share
1 answer

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

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) {
        ... 
    }
})

override ;)

+5

Source: https://habr.com/ru/post/1678443/


All Articles