Android應用--QR的產生(二維碼)

來源:互聯網
上載者:User

    二維碼現在隨處可見,使用Android代碼根據輸入的字串產生二維碼其實也很簡單,其中需要引用一個Google開源的包--ZXing。下面這個例子裡包含條碼和QR碼的產生和解析,下面講解二維碼的產生。首先,給出實現的: 產生二維碼的步驟如下:1.首先使用者在編輯框中輸入需要產生的字串內容2.點擊下方的按鈕3.按鈕下方的ImageView控制項顯示產生的二維碼 下面給出實現的具體代碼:1.介面的布局[html] <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:background="@android:color/white"      android:orientation="vertical" >        <Button          android:id="@+id/btn_scan_barcode"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:layout_marginTop="30dp"          android:text="Open camera" />            <LinearLayout    www.2cto.com        android:orientation="horizontal"          android:layout_marginTop="10dp"          android:layout_width="fill_parent"          android:layout_height="wrap_content">                    <TextView           android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:textColor="@android:color/black"          android:textSize="18sp"          android:text="Scan result:" />                    <TextView           android:id="@+id/tv_scan_result"          android:layout_width="fill_parent"          android:textSize="18sp"          android:textColor="@android:color/black"          android:layout_height="wrap_content" />      </LinearLayout>            <EditText           android:id="@+id/et_qr_string"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:layout_marginTop="30dp"          android:hint="Input the text"/>            <Button          android:id="@+id/btn_add_qrcode"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:text="Generate QRcode" />            <ImageView           android:id="@+id/iv_qr_image"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_marginTop="10dp"          android:layout_gravity="center"/>    </LinearLayout>   2.產生二維碼的代碼[java]  package com.zxing.encoding;    import java.util.Hashtable;    import android.graphics.Bitmap;    import com.google.zxing.BarcodeFormat;  import com.google.zxing.EncodeHintType;  import com.google.zxing.MultiFormatWriter;  import com.google.zxing.WriterException;  import com.google.zxing.common.BitMatrix;  /**  * @author Ryan Tang  *  */  public final class EncodingHandler {      private static final int BLACK = 0xff000000;            public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {          Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");           BitMatrix matrix = new MultiFormatWriter().encode(str,                  BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);          int width = matrix.getWidth();          int height = matrix.getHeight();          int[] pixels = new int[width * height];                    for (int y = 0; y < height; y++) {              for (int x = 0; x < width; x++) {                  if (matrix.get(x, y)) {                      pixels[y * width + x] = BLACK;                  }              }          }          Bitmap bitmap = Bitmap.createBitmap(width, height,                  Bitmap.Config.ARGB_8888);          bitmap.setPixels(pixels, 0, width, 0, 0, width, height);          return bitmap;      }  }   3.Activity上的操作實現[java]  package com.ericssonlabs;    import com.google.zxing.WriterException;  import com.zxing.activity.CaptureActivity;  import com.zxing.encoding.EncodingHandler;    import android.app.Activity;  import android.content.Intent;  import android.graphics.Bitmap;  import android.os.Bundle;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.EditText;  import android.widget.ImageView;  import android.widget.TextView;  import android.widget.Toast;    public class BarCodeTestActivity extends Activity {      /** Called when the activity is first created. */      private TextView resultTextView;      private EditText qrStrEditText;      private ImageView qrImgImageView;            @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);                    resultTextView = (TextView) this.findViewById(R.id.tv_scan_result);          qrStrEditText = (EditText) this.findViewById(R.id.et_qr_string);          qrImgImageView = (ImageView) this.findViewById(R.id.iv_qr_image);                    Button scanBarCodeButton = (Button) this.findViewById(R.id.btn_scan_barcode);          scanBarCodeButton.setOnClickListener(new OnClickListener() {                            @Override              public void onClick(View v) {                  Intent openCameraIntent = new Intent(BarCodeTestActivity.this,CaptureActivity.class);                  startActivityForResult(openCameraIntent, 0);              }          });                    Button generateQRCodeButton = (Button) this.findViewById(R.id.btn_add_qrcode);          generateQRCodeButton.setOnClickListener(new OnClickListener() {                            @Override              public void onClick(View v) {                  try {                      String contentString = qrStrEditText.getText().toString();                      if (!contentString.equals("")) {                          Bitmap qrCodeBitmap = EncodingHandler.createQRCode(contentString, 350);                          qrImgImageView.setImageBitmap(qrCodeBitmap);                      }else {                          Toast.makeText(BarCodeTestActivity.this, "Text can not be empty", Toast.LENGTH_SHORT).show();                      }                                        } catch (WriterException e) {                      // TODO Auto-generated catch block                      e.printStackTrace();                  }              }          });      }        @Override      protected void onActivityResult(int requestCode, int resultCode, Intent data) {          super.onActivityResult(requestCode, resultCode, data);          if (resultCode == RESULT_OK) {              Bundle bundle = data.getExtras();              String scanResult = bundle.getString("result");              resultTextView.setText(scanResult);          }      }  }   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.