Search code examples
androidandroid-jetpack-composeandroid-cameraandroid-camera2android-camerax

CameraX touch focus issue with Jetpack Compose


AndroidView(modifier = Modifier.fillMaxSize(),factory = {
            PreviewView(it).apply {
                this.controller = controller
                controller.bindToLifecycle(lifecycleOwner)
                implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                setOnTouchListener { _, event ->
                    val focusX = event.x // Map coordinates to focus points
                    val focusY = event.y
                    controller.isTapToFocusEnabled(focusX,focusY) // Assuming focus control API is available
                    true // Consume touch event
                }
            }
        })

Error

Too many arguments for public open fun isTapToFocusEnabled(): Boolean defined in androidx.camera.view.LifecycleCameraController

The camera works but I wanted to add touch focus but I'm having a problem that I can't find the solution and I'm having trouble finding resources with Jetpack Compose.I removed focusX,focusY and ran it. My device (Redmi Note 11 Pro, Android11)


Solution

  • As per the documentation of CameraController.isTapToFocusEnabled(), it does not take any argument and simply returns whether the tap-to-focus feature is enabled, i.e. it is not used to explicitly trigger tap-to-focus which you seem to be thinking.

    https://developer.android.com/reference/androidx/camera/view/CameraController#isTapToFocusEnabled()

    So, controller.isTapToFocusEnabled(focusX,focusY) leads to an error while controller.isTapToFocusEnabled() should work fine.

    The doc also mentions that it should be enabled by default (you can disable/re-enable it with the CameraController.setTapToFocusEnabled(boolean) API). So, the feature is already enabled by default and you don't need to do anything further to ensure focusing is happening according to tap event.

    If you want to know whether the tap was applied or successful, you can observe the LiveData returned by CameraController#getTapToFocusState() API instead. As the document explains, it will tell you whether tap-to-focus had started or completed or failed. How exactly you use that info will depend on what exactly your requirements though. For example, you can simply notify the user via a toast message or maybe do some UI change at the location of tap event.