1. 程式人生 > >掃描,生成二維碼

掃描,生成二維碼

在這裡插入圖片描述

掃描,生成二維碼

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="開啟掃描"
     />
<EditText
    android:id="@+id/edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="請輸入"/>
<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="獲取二維碼"/>

<ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:srcCompat="@tools:sample/avatars" />

public class MainActivity extends AppCompatActivity {

private Button btn,btn1;
private EditText edit;
private ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = findViewById(R.id.button);
    btn1 = findViewById(R.id.button1);
    edit = findViewById(R.id.edit);
    image = findViewById(R.id.image);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,CaptureActivity.class);
            startActivityForResult(intent,1);
        }
    });
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String s = edit.getText().toString();
            if(TextUtils.isEmpty(s)){
                return;
            }
            Bitmap bitmap = CodeUtils.createImage(s, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
            image.setImageBitmap(bitmap);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1){
        if(data!=null){
            Bundle bundle = data.getExtras();
            if(bundle==null){
                return;
            }
            if(bundle.getInt(CodeUtils.RESULT_TYPE)==CodeUtils.RESULT_SUCCESS){
                String string = bundle.getString(CodeUtils.RESULT_STRING);
                Toast.makeText(this,"解析結果"+string,Toast.LENGTH_SHORT).show();
            }else if(bundle.getInt(CodeUtils.RESULT_TYPE)==CodeUtils.RESULT_FAILED){
                Toast.makeText(this,"掃描失敗",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
}