思路导入依赖库zxing3.3.3 这是目前最新的版本。导入方式file>>project structure>>app>>dependencis>>点击加号>>选择library>>输入zxing 3.3.3就好了。也可以去网上直接下依赖包,然后再本地导入libs,在bulid.gradle(module.app)中写file("libs/core3.3.3")
直接上代码
MainActivity代码
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init_Viw();
}
public void zxing(String string){
try {
;
BitMatrix bitMatrix = new QRCodeWriter().encode(string, BarcodeFormat.CODE_93, 250, 250);
int fixbit[]=new int[bitMatrix.getWidth()*bitMatrix.getHeight()];
for (int y=0;y<bitMatrix.getHeight();y++){
for (int x=0;x<bitMatrix.getWidth();x++){
if (bitMatrix.get(x,y)){
fixbit[x+y*bitMatrix.getWidth()]= Color.BLACK;
}else{
fixbit[x+y*bitMatrix.getWidth()]=Color.WHITE;
}
}
}
Bitmap bitmap=Bitmap.createBitmap(fixbit,bitMatrix.getWidth(),bitMatrix.getHeight(), Bitmap.Config.ARGB_8888);
imageView.setImageBitmap(bitmap);
}catch (WriterException e){
}
}
public void init_Viw(){
button=(Button)findViewById(R.id.start);
editText=(EditText)findViewById(R.id.edit);
imageView=(ImageView)findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getText=editText.getText().toString();
zxing(getText);
}
});
}
}
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/start"
android:text="start"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="260dp"
android:id="@+id/image"/>
</LinearLayout>