how to start Zxing on a Fragment?

后端 未结 5 660
无人共我
无人共我 2021-02-06 15:30

i have an activity that holds Two Fragments, i want to run ZXING scanner on one of the fragments,

currently i do this on another activity like this >

         


        
5条回答
  •  臣服心动
    2021-02-06 16:09

    All the above answers are correct and i wanted to add how I did it.

    Step 1:

    implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    implementation 'com.google.zxing:core:3.2.1'
    

    Step 2: In My activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    Step 3: In my fragment

    requestCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Request camera
                IntentIntegrator integrator = IntentIntegrator.forSupportFragment(ScanFrag.this);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
                integrator.setPrompt("Scan QR code");
                integrator.setCameraId(0);
                integrator.setBeepEnabled(true);
                integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();
            }
        });
    

    And I override

     @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(requestCode == IntentIntegrator.REQUEST_CODE) {
            if (result != null) {
                if (result.getContents() == null) {
                    Log.d("ScanFrag", "Cancelled scan");
                    Toast.makeText(getContext(), "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    Log.d("ScanFrag", "Scanned | " + result.getContents());
                    Toast.makeText(getContext(), "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    

    Hope it will help someone looking how to use xzing from a fragment

提交回复
热议问题