How to implement QR code scanner in Fragment in po

2019-01-27 05:39发布

问题:

I am developing an application,In this application I have to implement QR code scanner, I can achieve this thing easily in activity with the help of Zxing library but the thing is that the scanner should be in fragment and the Fragment added in ViewPager and I also want customise the view of scanner.

回答1:

Use this Library for QR code scanner it is the Modification of ZXING Scanner project for easy Android QR-Code detection.QR Code Scanner



回答2:

For Android Studio Users

repositories {
 maven {
            url "https://jitpack.io"
    }
 }

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

First of all, you need to to trigger an intent by virtue of which camera gets open (Scanner).

Intent intent = new Intent("com.google.zxing.client.android.SCAN");                
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

Then , If trigerred within a Fragment then write, else you will get your request code wrong.

getActivity().startActivityForResult(intent, 0);

If From Activity

startActivityForResult(intent, 0);

Then, it must be an Activity where you need your results captured by the scanner, I have captured and thus displayed in a Toast.

 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
              Toast.makeText(this,contents,Toast.LENGTH_LONG).show();
                // Handle successful scan
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

Finally, Index it in manifest File, Use of intent filters enables it to recognise its source and function

<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
        android:clearTaskOnLaunch="true"
        android:stateNotNeeded="true">
        <intent-filter>
            <action android:name="com.google.zxing.client.android.SCAN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>