如何使用CameraX搭配PreviewView?相关技术实现疑问咨询
Hey there! I totally get how frustrating it can be when you can’t find clear, step-by-step guidance for pairing CameraX with PreviewView—let’s walk through this from start to finish so you can get your camera feed up and running smoothly.
1. Add Required Dependencies
First things first, make sure you’ve got the right CameraX libraries in your module-level build.gradle (or build.gradle.kts for Kotlin DSL):
dependencies { // CameraX core functionality implementation "androidx.camera:camera-core:1.3.0" // CameraX view library (for PreviewView) implementation "androidx.camera:camera-view:1.3.0" // Bind camera to activity/fragment lifecycle implementation "androidx.camera:camera-lifecycle:1.3.0" // Optional: Add extensions for features like HDR or night mode implementation "androidx.camera:camera-extensions:1.3.0" }
2. Insert PreviewView Into Your Layout
Add PreviewView to your activity/fragment layout—this is the view that will render the live camera feed. Here’s a simple ConstraintLayout example:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.camera.view.PreviewView android:id="@+id/previewView" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
3. Handle Camera Permissions
You can’t access the camera without the *CAMERA* permission. First, declare it in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera.any" />
Then, add dynamic permission checking in your activity/fragment (since CAMERA is a dangerous permission):
private val REQUEST_CAMERA_PERMISSION = 100 private fun checkCameraPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION ) } else { // Permission granted—start setting up the camera startCamera() } } // Handle permission request results override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CAMERA_PERMISSION) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startCamera() } else { Toast.makeText(this, "Camera permission is required to use this feature", Toast.LENGTH_SHORT).show() } } }
4. Initialize CameraX & Bind Preview Use Case
This is the core logic that connects CameraX to your PreviewView. Create a startCamera() function:
private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ // Get the camera provider to manage camera instances val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Create the preview use case val preview = Preview.Builder() .build() .also { // Attach the PreviewView's surface provider to the preview use case it.setSurfaceProvider(previewView.surfaceProvider) } // Select the back camera by default (use DEFAULT_FRONT_CAMERA for front camera) val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind any existing use cases before rebinding cameraProvider.unbindAll() // Bind the preview use case to the camera and lifecycle cameraProvider.bindToLifecycle( this, cameraSelector, preview ) } catch(exc: Exception) { Log.e("CameraXSetup", "Failed to bind use cases", exc) } }, ContextCompat.getMainExecutor(this)) }
5. Bonus: Customize Preview Behavior
Tweak how the camera feed fits into the PreviewView by adjusting the scale type:
// Options include: FIT_CENTER, FILL_CENTER, FILL_START, FILL_END previewView.scaleType = PreviewView.ScaleType.FILL_CENTER
To switch between front/back cameras, just create a new CameraSelector (like CameraSelector.DEFAULT_FRONT_CAMERA) and rebind the use cases.
That’s all! With these steps, you should have a working live camera preview using CameraX and PreviewView. If you run into specific bugs or edge cases, feel free to share details—I’m happy to help troubleshoot further.
内容的提问来源于stack exchange,提问作者Mohamed Ben Romdhane

