fix: camera preview not displaying after view remount #57
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix camera preview not displaying after view remount
Problem
When
CameraViewcomponent is unmounted and remounted (e.g., navigating away and back to the screen), the camera preview stops displaying even though scanning continues to work.Root cause: When the view is unmounted,
onDetachedFromWindow()callsreleaseCamera()which setspreviewView = null. When the view is remounted, the newpreviewViewinstance is not automatically bound to the camera manager, sobindCameraUseCases()tries to set the surface provider on a null reference:This results in a camera that scans barcodes successfully but shows no preview image.
Solution
Added
bindPreviewView()call inonAttachedToWindow()lifecycle method.When the view is reattached to the window:
setupLayoutHack()restarts the layout callbackbindPreviewView(previewView)re-binds the new preview view instance to the camera managerbindCameraUseCases()is called automatically with the correctpreviewViewreferenceChanges
override fun onAttachedToWindow() { super.onAttachedToWindow() // Restart layout callback when view is reattached setupLayoutHack() + // Rebind the preview view to camera manager when reattached + cameraManager?.bindPreviewView(previewView) }Testing
Tested on Android with the following scenario:
CameraViewBenefits
releaseCamera()still works as intended