今天来个扫描二维码的功能,简单实用,还可自行更改(二维码部分是在网上找的一个moudle,直接导入实用即可,这里提前感谢大佬们)
1、首先,新建一个Activity,来个Button(调起扫码界面),再来个TextView(展示扫码结果)
<?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=".view.activity.ScanningActivity">
<Button
android:id="@+id/scanBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout><?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=".view.activity.ScanningActivity">
<Button
android:id="@+id/scanBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
2、界面写完之后,先将moudle导入到你的工程里面(moudle代码文件文章末尾给出),怎么导入moudel我就不说了哈,记得在你的主moudle中添加下方代码
implementation project(':zxing-lib')
3、Activity代码如下:
public class ScanningActivity extends AppCompatActivity {
private static final String TAG = "VideoDrawActivity";
private Button scanBtn;
private TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_draw);
scanBtn = findViewById(R.id.scanBtn);
tvResult = findViewById(R.id.tvResult);
scanBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 二维码扫码
Intent intent = new Intent(ScanningActivity.this, CaptureActivity.class);
startActivityForResult(intent, Constant.REQ_QR_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//扫描结果回调
if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
//将扫描出的信息显示出来,拿到信息之后做什么那就是你自己的事情了
tvResult.setText(scanResult);
}
}
}
4、对了,AndroidManifest中记得加上这个
<activity android:name="com.google.zxing.activity.CaptureActivity"/>
好啦,文本结束,是不是很简单呢!你也可以在zxing-lib中自己修改布局文件啥的!
moudle资源在这里!!!(或者直接去我博客主页里面,资源下载就行)
https://pan.baidu.com/s/1Ck1yXYAoYpiTm64N7uTuPg
提取码:hw96