Android Jetpack Compose + CameraX

Christian Stowers
2 min readNov 12, 2023

--

This one is short and sweet.

Currently there isn’t an implementation of CameraX within Jetpack Compose. Thankfully, within Compose, there exists a beautiful nod back to our imperative UI days: the AndroidView composable! This allows the use of Views within a Composable. For example, the below code implements the CameraX PreviewView which displays the camera feed.

val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
val cameraController: LifecycleCameraController = remember { LifecycleCameraController(context) }

AndroidView(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
factory = { context ->
PreviewView(context).apply {
setBackgroundColor(Color.White.toArgb())
layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
scaleType = PreviewView.ScaleType.FILL_START
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
}.also { previewView ->
previewView.controller = cameraController
cameraController.bindToLifecycle(lifecycleOwner)
}
}
)

This of course should be placed within whatever Compose UI structure you desire (for example, within a Scaffold composable) which will be covered in a separate article soon.

Now adjust those glasses and turn your introductory understanding of AndroidView into a natural element of your coding knowledge. Check out the Android AndroidView documentation.

For more information regarding CameraX, take a gander at the Android CameraX documentation.

How often do we come across small, incrementally helpful tooltips, coding hacks, and the like amidst those weekend and late-night slogs grinding to get our project code to compile or look less bad or just stop seeing so much red? Pay it forward, and best of luck this week.

A big thank you to Yanneck Reiß for this Youtube tutorial that broaches this topic. Check him out here!

--

--

No responses yet