1. Control
1.1 button
Get button:
Button btn_scan_view=(Button) findViewById(R.id.button_get);
Button click event:
//Click the start generation button to listen for events btn_get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Click event content } });
1.2 Input box
Input box:
EditText edittext=findViewById(R.id.editTextText);//Input box
Get the input content:
String input= edittext.getText().toString();
1.3 Images
Get the image control:
ImageView img_view=(ImageView)findViewById(R.id.imageView);
Fill the control with an image:
img_view.setImageBitmap();
2. Page jump
2.1 Jump to custom page
Use Intent to implement page jump
First, we need to create a new Android Activity. In Android Studio, this can be achieved by following these steps:
In the project’s structure view, right-click app -> New -> Activity -> Blank Activity, then name the new Activity and choose which folder to place it in.
In the AndroidManifest.xml file, we need to register a category for the new Activity.
//Listen to the button, if clicked, jump ntent intent = new Intent(); //The previous one (MainActivity.this) is the current page, and the next one is the next page to jump to. intent.setClass(MainActivity.this,ScanActivity.class);//ScanActivity is modified to the page to be redirected startActivity(intent);
3. Code example (generate and scan QR code)
3.1 Creating projects and preparations
Create a project and modify the image speedup (settings.gradle.kts) file to:
pluginManagement { repositories { maven { setUrl("https://maven.aliyun.com/repository/public") } maven { setUrl("https://maven.aliyun.com/repository/central") } google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { maven { setUrl("https://maven.aliyun.com/repository/public") } maven { setUrl("https://maven.aliyun.com/repository/central") } google() mavenCentral() } }
Add the jar package to maven and add in build.gradle.kts:
implementation("com.journeyapps:zxing-android-embedded:3.6.0")
3.2 Main page (generate QR code):
Code:
package com.example.week08_or; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.util.Hashtable; public class MainActivity extends AppCompatActivity { Button btn_get; Button btn_scan_view; ImageView img_view; EditText edittext; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_get=(Button) findViewById(R.id.button_get); img_view=(ImageView)findViewById(R.id.imageView); btn_scan_view=(Button)findViewById(R.id.button_page);//Jump page edittext =findViewById(R.id.editTextText);//input box //Click the start generation button to listen for events btn_get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input= edittext.getText().toString(); //Call the CreateUtil class to generate a QR code and display it on the interface img_view.setImageBitmap(createQRCode(input,img_view.getWidth(),img_view.getHeight())); } }); btn_scan_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Listen to the button, if clicked, jump Intent intent = new Intent(); //The previous one (MainActivity.this) is the current page, and the next one is the next page to jump to. intent.setClass(MainActivity.this,ScanActivity.class); startActivity(intent); } }); } //Convert the input string into an image public Bitmap createQRCode(String codestring, int width, int height){ try { //First determine the legality of the parameters, requiring that the string content cannot be empty or the image length and width must be greater than 0 if (TextUtils.isEmpty(codestring)||width<=0||height<=0){ return null; } //Set the relevant parameters of the QR code and generate a BitMatrix (bit matrix) object Hashtable<EncodeHintType,String> hashtable=new Hashtable<>(); hashtable.put(EncodeHintType.CHARACTER_SET,"utf-8"); //Set the character transcoding format hashtable.put(EncodeHintType.ERROR_CORRECTION,"H"); //Set the fault tolerance level hashtable.put(EncodeHintType.MARGIN,"2"); //Set blank margins //encode needs to throw and handle exceptions BitMatrix bitMatrix=new QRCodeWriter().encode(codestring, BarcodeFormat.QR_CODE,width,height,hashtable); //Create a pixel array again and assign color values to the array elements based on the bit matrix int[] pixel=new int[width*width]; for (int h=0;h<height;h + + ){ for (int w=0;w<width;w + + ){ if (bitMatrix.get(w,h)){ pixel[h*width + w]= Color.BLACK; //Set black color block }else{ pixel[h*width + w]=Color.WHITE; //Set the white color block } } } //Create bitmap object //Set the color value of each pixel of Bitmap according to the pixel array, and then return the Bitmap object Bitmap qrcodemap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888); qrcodemap.setPixels(pixel,0,width,0,0,width,height); return qrcodemap; }catch (WriterException e){ return null; } } }
layout file:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@ + id/imageView" android:layout_width="301dp" android:layout_height="283dp" android:layout_marginStart="50dp" android:layout_marginEnd="50dp" android:layout_marginBottom="149dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@ + id/button_get" app:layout_constraintVertical_bias="1.0" app:srcCompat="@drawable/ic_launcher_background" /> <Button android:id="@ + id/button_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="21dp" android:layout_marginBottom="529dp" android:text="Generate" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@ + id/button_page" app:layout_constraintTop_toBottomOf="@ + id/editTextText" /> <EditText android:id="@ + id/editTextText" android:layout_width="355dp" android:layout_height="78dp" android:ems="10" android:inputType="text" android:text="Enter the string to be generated" app:layout_constraintBottom_toTopOf="@ + id/button_page" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@ + id/button_page" android:layout_width="108dp" android:layout_height="59dp" android:layout_marginStart="23dp" android:text="Scan code page" app:layout_constraintBaseline_toBaselineOf="@ + id/button_get" app:layout_constraintEnd_toStartOf="@ + id/button_get" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
3.3 Scan the QR code
Code:
package com.example.week08_or; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.journeyapps.barcodescanner.CaptureActivity; public class ScanActivity extends AppCompatActivity { Button btn_scan; Button btn_back; TextView textView; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan);//Binding page btn_scan=(Button)findViewById(R.id.btn_scan); btn_back=(Button) findViewById(R.id.button2); textView=(TextView)findViewById(R.id.textView); //Scan QR code button click event btn_scan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //.QR_CODE_TYPES QR code //ONE_D_CODE_TYPES barcode //ALL_CODE_TYPES All types new IntentIntegrator(ScanActivity.this).setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)//Type of scan code, optional: one-dimensional code, two-dimensional code, one/two-dimensional code .setPrompt("Please aim at the QR code")//Set prompt .setCameraId(0)//Select the camera, you can use front or rear .setBeepEnabled(false)//Whether to turn on the sound, there will be a "beep" after scanning the code //.setBarcodeImageEnabled(true)// Generate a QR code image after scanning the code .setCaptureActivity(CaptureActivity.class) .initiateScan();//Initialize code scanning } }); //return to previous page btn_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } #Callback function to process scan results @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if(result != null) { if(result.getContents() == null) { Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show(); textView.setText(result.getContents()); } } else { super.onActivityResult(requestCode, resultCode, data); } } }
Layout file:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@ + id/btn_scan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="104dp" android:layout_marginBottom="90dp" android:text="Scan" app:layout_constraintBottom_toTopOf="@ + id/textView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@ + id/textView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="55dp" android:layout_marginEnd="55dp" android:layout_marginBottom="275dp" android:text="Scan results" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@ + id/btn_scan" /> <Button android:id="@ + id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="33dp" android:layout_marginTop="5dp" android:text="Return" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@ + id/btn_scan" /> </androidx.constraintlayout.widget.ConstraintLayout>
3.2.3 Customized scan window
need to
setCaptureActivity(CaptureActivity.class)
change into:
setCaptureActivity(CustomCaptureActivity.class) //CustomCaptureActivity is the custom activity name.
Activity:
package com.example.week08_or; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.KeyEvent; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.journeyapps.barcodescanner.CaptureManager; import com.journeyapps.barcodescanner.DecoratedBarcodeView; public class CustomCaptureActivity extends AppCompatActivity { private CaptureManager capture; private DecoratedBarcodeView barcodeScannerView; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_capture); // Custom layout barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.dbv_custom); capture = new CaptureManager(this, barcodeScannerView); capture.initializeFromIntent(getIntent(), savedInstanceState); capture.decode(); } @Override protected void onResume() { super.onResume(); capture.onResume(); } @Override protected void onPause() { super.onPause(); capture.onPause(); } @Override protected void onDestroy() { super.onDestroy(); capture.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); capture.onSaveInstanceState(outState); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); capture.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } }
layout:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.journeyapps.barcodescanner.DecoratedBarcodeView android:id="@ + id/dbv_custom" android:layout_width="372dp" android:layout_height="683dp" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:zxing_preview_scaling_strategy="fitXY" tools:layout_editor_absoluteY="19dp" tools:ignore="MissingConstraints" /> </androidx.constraintlayout.widget.ConstraintLayout>