在build.gradle文件中添加以下依赖:
dependencies {
implementation 'androidx.camera:camera-camera2:1.0.0-beta06'
implementation 'androidx.camera:camera-lifecycle:1.0.0-beta06'
implementation 'androidx.camera:camera-view:1.0.0-alpha28'
}
接着,在布局文件中添加以下代码:
最后,在activity中获取PreviewView实例并将其用于相机预览:
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
val previewView = findViewById(R.id.previewView)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(previewView.createSurfaceProvider())
}
val camera = cameraProvider.bindToLifecycle(
this, CameraSelector.DEFAULT_BACK_CAMERA, preview)
}, ContextCompat.getMainExecutor(this))