CameraX 的 OnImageCapturedListener 报错

OnImageCapturedListener of CameraX gives an error

我正在测试新的 CameraX API 并且我有以下代码行:

imageCapture.takePicture(executor, object:ImageCapture.OnImageCapturedListener{
    // do some work when image is captured 
})

但是参数object:ImageCapture.OnImageCapturedListener是用红色下划线标出的。 Android Studio 告诉我:"This type has a constructor and thus must be initialized here"

注意:上面的代码是在 Button 的点击侦听器中调用的。

下面你可以看到 ImageCapture class 的另一个监听器 OnImageSavedListener。使用此界面我没有错误。

findViewById<ImageButton>(R.id.capture_button).setOnClickListener {
            val file = File(externalMediaDirs.first(),
                "${System.currentTimeMillis()}.jpg")

            imageCapture.takePicture(file, executor,
                object : ImageCapture.OnImageSavedListener {

                    override fun onError(
                        imageCaptureError: ImageCapture.ImageCaptureError,
                        message: String,
                        exc: Throwable?
                    ) {
                        val msg = "Photo capture failed: $message"
                        Log.e("CameraXApp", msg, exc)
                        viewFinder.post {
                            Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onImageSaved(file: File) {
                        val msg = "Photo capture succeeded: ${file.absolutePath}"
                        Log.d("CameraXApp", msg)
                        viewFinder.post {
                            Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        }

                        var bitmap:Bitmap = viewFinder.bitmap
                        runOnUiThread { imageView.setImageBitmap(bitmap) }
                    }
                })

我对此没有问题,但是当我使用 OnImageCapturedListener 并将 onImageSaved 回调替换为 onCaptureSuccess 回调时,我收到如上所述的错误

Try out this code.

imageCapture.takePicture(executor,object :ImageCapture.OnImageCapturedListener(){
            override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
                super.onCaptureSuccess(image, rotationDegrees)  

                // capture image 

                }
             override fun onError(
                imageCaptureError: ImageCapture.ImageCaptureError,
                message: String,
                cause: Throwable?) {
                super.onError(imageCaptureError, message, cause)
                // error in capturing
            }

        })