journeyapps / zxing-android-embedded

Barcode scanner library for Android, based on the ZXing decoder
https://journeyapps.com/
Apache License 2.0
5.68k stars 1.26k forks source link

Scanner works only in portrait mode when called from a fragment #681

Closed mateusz-bak closed 2 years ago

mateusz-bak commented 2 years ago

Description of the problem:

Scanner works only in portrait mode when called from a fragment.

Which library version are you using? 4.3.0

Which phone/tablet are you using, and which Android version does it run? OnePlus 8T, Android 11

Does the same happen on other devices or an emulator? Yes

Can you reproduce the issue in the sample project included with the library? If not, can you provide your own sample project or sample code that produces this error?

My Fragment code:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = (activity as MainActivity).booksViewModel
        mainActivity = activity as MainActivity

        val barcodeLauncher = registerForActivityResult(
            ScanContract()
        ) { result: ScanIntentResult ->
            if (result.contents == null) {
                Toast.makeText(listActivity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(
                    listActivity,
                    "Scanned: " + result.contents,
                    Toast.LENGTH_LONG
                ).show()
            }
        }

        val options = ScanOptions()
        options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES)
        options.setPrompt("Scan a barcode")
        options.setCameraId(0) // Use a specific camera of the device
        options.setBeepEnabled(false)
        options.setBarcodeImageEnabled(true)
        options.setOrientationLocked(true)
        barcodeLauncher.launch(options)
    }

Manifest code for the main activity:

        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            tools:replace="screenOrientation">

        </activity>

Doesn't matter whatever I set in android:screenOrientation or in options.setOrientationLocked, the scanner always opens in landscape mode.

rkistner commented 2 years ago

In the manifest, you need to set the orientation for the Activity used for capturing (com.journeyapps.barcodescanner.CaptureActivity by default), not your .MainActivity.

mateusz-bak commented 2 years ago

It works now, I didn't understand it properly before. Thank you!