【发布时间】:2021-08-12 09:51:49
【问题描述】:
我已按照here to get CameraX setup 的步骤操作,现在我正在尝试让前置摄像头按钮工作。
这是我的设置代码:
private lateinit var preview: Preview
private fun startCamera() {
// Create configuration object for the viewfinder use case
val previewConfig = PreviewConfig.Builder().apply {
setLensFacing(CameraX.LensFacing.BACK)
}.build()
// Build the viewfinder use case
preview = Preview(previewConfig)
// Every time the viewfinder is updated, recompute layout
preview.setOnPreviewOutputUpdateListener {
// To update the SurfaceTexture, we have to remove it and re-add it
val parent = viewFinder.parent as ViewGroup
parent.removeView(viewFinder)
parent.addView(viewFinder, 0)
viewFinder.surfaceTexture = it.surfaceTexture
updateTransform()
}
// Bind use cases to lifecycle
CameraX.bindToLifecycle(this, preview)
}
当用户单击“切换”按钮时,我重新配置预览以使用前置摄像头,然后重新初始化预览。
private fun initSwitchButton(view: View) {
switchButton = view.findViewById(R.id.switch_button)
switchButton.setOnClickListener {
val previewConfig = PreviewConfig.Builder().apply { setLensFacing(CameraX.LensFacing.FRONT) }.build()
preview = Preview(previewConfig)
}
}
但是,这不会切换到前置摄像头。我错过了什么?
【问题讨论】:
-
既然您正在创建一个新的
Preview实例,您是否不需要在这个新的Preview上运行第一个代码sn-p 中的setOnPreviewOutputUpdateListener和bindToLifecycle()位? (除了清理旧的Preview实例,如果这还没有完成的话)我还没有使用过 CameraX,所以我可能不正常——这只是比较和对比你的两个代码 sn-ps . -
刚刚找到了一个示例,github.com/android/camera/blob/master/CameraXBasic/app/src/main/…,看起来您需要再次致电
bindToLifecycle。当我找到一个干净的解决方案时,我会更新答案!