Article reproduced from Https://github.com/yipianfengye/android-zxingLibrary
Before we introduce the scan library, let's take a look at its specific usage, and see if a few lines of code can integrate the QR code scanning function.
- Performing compile operations in the module's Build.gradle
compile ‘cn.yipianfengye.android:zxing-library:2.1‘
- To perform an initialization operation in the demo application
@Override public void onCreate() { super.onCreate(); ZXingLibrary.initDisplayOpinion(this); }
- Perform an open scan QR code interface operation
/** * 打开默认二维码扫描界面 */ button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CaptureActivity.class); startActivityForResult(intent, REQUEST_CODE); } });
The request_code here is the int type constant that we define.
- Receive scan results in activity's Onactivityresult method
/** * 处理二维码扫描结果 */ if (requestCode == REQUEST_CODE) { //处理扫描结果(在界面上显示) if (null != data) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { String result = bundle.getString(CodeUtils.RESULT_STRING); Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show(); } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show(); } } }
How is it easy? Below we can look at the specific implementation effect:
Execution effect:
But is it too simple, if I want to choose the image analysis? Don't worry, the resolution of the two-dimensional code image is also supported
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");startActivityForResult(intent, REQUEST_IMAGE);
- Get the user selected picture in the activity's Onactivityresult method and call the QR Code image parsing API
if (Requestcode = = request_image) {if (data! = null) {URI uri = Data.getdata (); Contentresolver CR = Getcontentresolver (); try {Bitmap mbitmap = MediaStore.Images.Media.getBitmap (CR, URI);//appears to Bitmap picture Code Utils.analyzebitmap (Mbitmap, New Codeutils.analyzecallback () {@Override Pub LIC void onanalyzesuccess (Bitmap mbitmap, String result) {Toast.maketext (mainactivity.this, "solution Analysis Result: "+ result, Toast.length_long)." Show (); } @Override public void onanalyzefailed () {Toast . Maketext (Mainactivity.this, "Parsing the QR code failed", Toast.length_long). Show (); } }); if (mbitmap! = null) {mbitmap.recycle (); }} catch (Exception e) { E.printstacktrace (); } }
Execution effect
With the default QR code scanning interface, but also the two-dimensional code image of the resolution, perhaps some students will say if I want to customize the display of the UI? No matter also support drip.
- Customizing the Display Scan UI
Because our scanning components are implemented through fragment, it is easy to customize the scanning UI.
- Defining layout layouts files in new activity
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/ Apk/res/android "android:id=" @+id/activity_second "android:layout_width=" match_parent "android:layout_height=" mat Ch_parent "> <button android:id=" @+id/second_button1 "android:layout_width=" Wrap_content "and roid:layout_height= "Wrap_content" android:text= "Cancel" android:layout_margintop= "20DP" Android:layout_ma rginleft= "20DP" android:layout_marginright= "20DP" android:layout_marginbottom= "10DP" Android:layout_g ravity= "Bottom|center_horizontal"/> <framelayout android:id= "@+id/fl_my_container" Android: Layout_width= "Match_parent" android:layout_height= "Match_parent" ></framelayout></framelayout> ;
The launch of Framelayout with ID Fl_my_container is the scanning component we need to replace, which means we will replace our defined scan fragment with the location of Framelayout with ID fl_my_container. And the button above is an extra control we added, where you can add any control, various UI effects, and so on. You can see the following in the activity initialization process.
- Perform fragment initialization operations in activity
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); /** * 执行扫面Fragment的初始化操作 */ CaptureFragment captureFragment = new CaptureFragment(); // 为二维码扫描界面设置定制化界面 CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera); captureFragment.setAnalyzeCallback(analyzeCallback); /** * 替换我们的扫描控件 */ getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit(); }
Where Analyzecallback is our definition of the scan callback function, its specific definition:
/** * QR Code parsing callback function */codeutils.analyzecallback Analyzecallback = new Codeutils.analyzecallback () {@Overri De public void onanalyzesuccess (Bitmap mbitmap, String result) {Intent resultintent = new Intent (); Bundle bundle = new bundle (); Bundle.putint (Codeutils.result_type, codeutils.result_success); Bundle.putstring (codeutils.result_string, RESULT); Resultintent.putextras (bundle); SecondActivity.this.setResult (RESULT_OK, resultintent); SecondActivity.this.finish (); } @Override public void onanalyzefailed () {Intent resultintent = new Intent (); Bundle bundle = new bundle (); Bundle.putint (Codeutils.result_type, codeutils.result_failed); Bundle.putstring (Codeutils.result_string, ""); Resultintent.putextras (bundle); SecondActivity.this.setResult (RESULT_OK, resultintent); SecondActivity.this.finiSH (); } };
If you look at it carefully, You will find that we call the Condeutils.setfragmentargs method, which is mainly used to modify the scanning interface scan box and transparent box relative position, and if not called, it will show the default component effect, and if the method is called, you can modify the scan box and the relative position of the transparent box and other UI effects, we can Take a look at the implementation of the My_camera layout file.
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/ Apk/res/android "xmlns:app=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Fill_parent "android:l ayout_height= "Fill_parent" > <surfaceview android:id= "@+id/preview_view" android:layout_width= "wrap _content "android:layout_height=" wrap_content "/> <com.uuzuche.lib_zxing.view.viewfinderview Android:id= "@+id/viewfinder_view" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" App:inner_width= "200DP" app:inner_height= "200DP" app:inner_margintop= "150DP" App:inner_corner_ Color= "@color/scan_corner_color" app:inner_corner_length= "30DP" app:inner_corner_width= "5DP" App:inne r_scan_bitmap= "@drawable/scan_image" app:inner_scan_speed= "app:inner_scan_iscircle=" false "/>& Lt;/framelayout>
Above our custom Scan control layout file, let's look at the default scan control's layout file:
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="fill_parent" > <SurfaceView android:id="@+id/preview_view" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.uuzuche.lib_zxing.view.ViewfinderView android:id="@+id/viewfinder_view" android:layout_width="wrap_content" android:layout_height="wrap_content" /></FrameLayout>
The main difference that can be found is that there are several custom scan box properties in the Custom Scan control:
<declare-styleable name="innerrect"> <attr name="inner_width" format="dimension"/><!-- 控制扫描框的宽度 --> <attr name="inner_height" format="dimension"/><!-- 控制扫描框的高度 --> <attr name="inner_margintop" format="dimension" /><!-- 控制扫描框距离顶部的距离 --> <attr name="inner_corner_color" format="color" /><!-- 控制扫描框四角的颜色 --> <attr name="inner_corner_length" format="dimension" /><!-- 控制扫描框四角的长度 --> <attr name="inner_corner_width" format="dimension" /><!-- 控制扫描框四角的宽度 --> <attr name="inner_scan_bitmap" format="reference" /><!-- 控制扫描图 --> <attr name="inner_scan_speed" format="integer" /><!-- 控制扫描速度 --> <attr name="inner_scan_iscircle" format="boolean" /><!-- 控制小圆点是否展示 --> </declare-styleable>
With these properties we can customize our scanning UI, such as customizing the scan UI:
Execution effect
Of course, if the above, you are still not satisfied with the customization of the UI, you can download my project directly, and then introduce lib-zxing module as your module, directly modify its code.
/** * 生成二维码图片 */ button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String textContent = editText.getText().toString(); if (TextUtils.isEmpty(textContent)) { Toast.makeText(ThreeActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show(); return; } editText.setText(""); mBitmap = CodeUtils.createImage(textContent, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)); imageView.setImageBitmap(mBitmap); } });
- Create a two-dimensional code image without logo
/** * 生成不带logo的二维码图片 */ button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String textContent = editText.getText().toString(); if (TextUtils.isEmpty(textContent)) { Toast.makeText(ThreeActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show(); return; } editText.setText(""); mBitmap = CodeUtils.createImage(textContent, 400, 400, null); imageView.setImageBitmap(mBitmap); } });
/** * 打开闪光灯 */CodeUtils.isLightEnable(true);/** * 关闭闪光灯 */ CodeUtils.isLightEnable(false);
Android integrated QR code scanning function