问题描述
我在布局资源文件中创建CameraPreview,并且我想通过单击导航图标按钮在AndroidView中显示此文件。
// navigation icon button
Icon(
vectorResource(id = R.drawable.ic_photo),modifier = Modifier.clickable(onClick = /* show CameraPreview */)
)
// compose CameraPreview
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
AndroidView(viewBlock = { ctx ->
/* get the CameraPreview */
})
}
// xml file
<androidx.camera.view.PreviewView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
解决方法
在可组合内容本身中创建PreviewView
的实例:
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
val previewView = remember { PreviewView(context) }
AndroidView(viewBlock = { previewView }) {
// Initialize your camera here
}
}