Introducing CameraViewfinder: Simplify Resizable Camera Preview on Android
This article explains how Android developers can use the new Jetpack CameraViewfinder component to implement reliable, resizable camera previews across diverse device form factors—including foldables and multi‑window modes—by adding the library, configuring layout XML, and handling surface requests with concise Kotlin code examples.
Android devices now come in many sizes and shapes, making camera preview implementation more complex, especially when handling window resizing, orientation changes, multi‑window, or foldable devices. Developers must avoid assumptions about fixed orientation, size, or exclusive camera access.
The Jetpack CameraViewfinder component provides a ready‑made solution that internally uses TextureView or SurfaceView , automatically correcting aspect ratio, scaling, and rotation, and works seamlessly with existing Camera2 code.
To use it, add the dependency to your app‑level build.gradle :
implementation "androidx.camera:camera-viewfinder:1.3.0-alpha01"After syncing, you can place the view in a layout just like any other View :
<androidx.camera.viewfinder.CameraViewfinder
android:id="@+id/view_finder"
app:scaleType="fitCenter"
app:implementationMode="performance"
android:layout_width="match_parent"
android:layout_height="match_parent"/>When creating a CameraCaptureSession , request a surface from the viewfinder instead of a TextureView :
fun startCamera() {
val previewResolution = Size(width, height)
val viewfinderSurfaceRequest = ViewfinderSurfaceRequest(previewResolution, characteristics)
val surfaceListenableFuture = cameraViewfinder.requestSurfaceAsync(viewfinderSurfaceRequest)
Futures.addCallback(surfaceListenableFuture, object : FutureCallback
{
override fun onSuccess(surface: Surface) { /* use surface to create CaptureSession */ }
override fun onFailure(t: Throwable) { /* handle error */ }
}, ContextCompat.getMainExecutor(context))
}CameraViewfinder works in resizable layouts, configuration changes, rotation, and multi‑window modes, and has been tested on many foldable devices. For advanced foldable UI, combine it with the Jetpack WindowManager library to adapt the preview area based on hinge position or device posture.
Additional resources include the official Android compatibility definition for camera orientation, the CameraX preview documentation, and sample code demonstrating handling posture changes on foldable devices.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.