The renderings are as follows:



Premise: after the import of zxing JAR began to operate, the old rule finally has the source code, the author layout default relative layout.

Step 1: Define the length, width and height of two-dimensional code and picture control


Step 2: After instantiating QRCodeWriter, draw the QR code using the for loop, and then load the image with the image control.

The source code is as follows:

Layout file: **

<Button android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="0dp" <ImageView android:id="@+id/ ImageView "android:id="@+id/ ImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="192dp" android:src="@drawable/ic_launcher_background" /> <EditText android:id="@+id/myeditText" android:layout_width="300dp" android:maxLines="1" android:layout_height="wrap_content" android:layout_below="@+id/mybutton" Android :layout_centerHorizontal="true" Android :ems="10" Android: Hint ="Copy the code

Java file:

public class MainActivity extends Activity implements View.OnClickListener { private int width = 300; private int height = 300; private ImageView imageView; private Bitmap bit; private Button mybutton; private EditText myeditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { imageView = (ImageView) findViewById(R.id.imageView); mybutton = (Button) findViewById(R.id.mybutton); mybutton.setOnClickListener(this); myeditText = (EditText) findViewById(R.id.myeditText); myeditText.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.mybutton: String name=myeditText.getText().toString(); If (name.equals("")){myedittext.seterror (" please enter content "); }else{ zxing(name); } break; } } private void zxing(String name){ QRCodeWriter qrCodeWriter = new QRCodeWriter(); Map<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // Remember to customize BitMatrix encode = null; try { encode = qrCodeWriter.encode(name, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException e) { e.printStackTrace(); } int[] colors = new int[width * height]; For (int I = 0; int I = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (encode.get(i, j)) { colors[i * width + j] = Color.BLACK; } else { colors[i * width + j] = Color.WHITE; } } } bit = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565); imageView.setImageBitmap(bit); }}Copy the code