Closed victorjaviermartin closed 5 years ago
Try using ViewStub! I did it and it worked. Sample:
activity_camera.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CNHScanActivity">
<ViewStub
android:id="@+id/camera_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/camera_view"
android:visibility="gone"/>
</RelativeLayout>
camera_view.xml
<?xml version="1.0" encoding="utf-8"?>
<io.fotoapparat.view.CameraView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Part of setup code in the activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set Activity's layout
setContentView(R.layout.activity_camera)
// Check camera permission
if (ActivityCompat.checkSelfPermission(
context!!,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
setUpCamera()
} else {
requestCameraPermission()
}
}
private fun setUpCamera() {
camera_stub.inflate()
fotoapparat = Fotoapparat(
context = context!!,
view = camera_view,
scaleType = ScaleType.CenterCrop,
lensPosition = activeCamera.lensPosition,
cameraConfiguration = activeCamera.configuration,
logger = loggers(
logcat()
)
)
fotoapparat.start()
}
private fun requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
Snackbar.make(
parentLayout, getString(R.string.permission_camera_explanation_cnh),
Snackbar.LENGTH_INDEFINITE).setAction(
"OK") {
requestPermissions(arrayOf(Manifest.permission.CAMERA),
PERMISSION_REQUEST_CAMERA
)
}
.show()
} else {
requestPermissions(arrayOf(Manifest.permission.CAMERA), PERMISSION_REQUEST_CAMERA)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != PERMISSION_REQUEST_CAMERA) {
return
}
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpCamera()
}
}
Sorry for the late reply, it looks like issue is resolved so I am closing this.
The ViewStub
approach worked for me. Thanks @rodrigovenancio
However, this still feels like a workaround.
To make things easier, it would be nice to let Fotoapparat
check for the permission automatically or to add a function onPermissionGranted()
to be called in that scenario.
Hi, after the permission question accepted, the preview is not working, the next time that I enter, then the preview works.
Fragment loaded in landscape mode `public class UpdateDniFragment extends Fragment implements Runnable {
} `