BÀI 87 - TẠO MÃ BARCODE TRONG ANDROID

  • Thêm thư viện này

implementation 'com.google.zxing:core:3.3.3'

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

  • Tạo cái view như này

<FrameLayout

android:layout_marginTop="10dp"

android:background="#FFFF"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<ImageView

android:id="@+id/imageView_MachineInformation_BarCodeSeriNumber"

android:src="@drawable/no_image"

android:layout_width="match_parent"

android:layout_height="60dp"

tools:ignore="ContentDescription" />

</FrameLayout>

  • Rồi code như này

private void PrintBarCodeSeriNumber(String text) {

if (text != null && text.length() > 0) {

Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable <>();

hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

Writer writer = new Code128Writer();

BitMatrix bitMatrix = null;

try {

bitMatrix = writer.encode(text, BarcodeFormat.CODE_128, 600, 200, hintMap);

} catch (WriterException e) {

showToast(e.toString());

}

int width = bitMatrix.getWidth();

int height = bitMatrix.getHeight();

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

for (int i = 0; i<width; i++) {

for (int t = 0; t<height; t++) {

bitmap.setPixel(i, t, bitMatrix.get(i, t) ? Color.BLACK : Color.WHITE);

}

}

imgSeriNumber.setImageBitmap(bitmap);

}

}