-
打开闪光灯
-
ScanQRcode完整代码
-
实现结果
-
最后注解
-
参考链接
=============================================================
随着互联网的发展,在网上的二维码种类和作用越来越多,因此我想着自己也实现生成二维码以及扫码。经过上网查资料发现,大多实现二维码功能的,主要都是靠集成了ZXing开源项目的功能,目前还有人在维护,足够我们学习使用。
- ZXing开源库链接https://github.com/zxing/zxing
================================================================
- 在ZXing开源库中我们可以看到它已经升级到了3.4.0,于是导入3.4.0的依赖
- 在build.gradle中添加依赖com.google.zxing:core:3.4.0
apply plugin: ‘com.android.application’
android {
compileSdkVersion 29
buildToolsVersion “29.0.3”
defaultConfig {
applicationId “com.example.qrcodetest”
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName “1.0”
testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
}
dependencies {
implementation fileTree(dir: ‘libs’, include: [’*.jar’])
implementation ‘androidx.appcompat:appcompat:1.1.0’
implementation ‘androidx.constraintlayout:constraintlayout:1.1.3’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.2.0’
implementation ‘com.google.zxing:core:3.4.0’
}
- 在activity_main.xml文件中添加两个按钮,一个是生成二维码,一个是扫描二维码,并在MainActivity中添加监听按钮点击,实现以下界面
- 创建一个名为GenerateQRcode的Activity,Android Studio自动生成其布局文件,布局文件改名为generate_qrcode.xml:放置一个
EditText
输入二维码内容、一个Button
监听操作以及一个ImageView
提供二维码的显示,对应的string在string.xml中添加
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height=“match_parent”
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_alignParentEnd=“true”
android:text="@string/firstTest"
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toTopOf=“parent” />
<Button
android:id="@+id/btn"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text="@string/generate_btn"
app:layout_constraintTop_toBottomOf="@+id/editText"
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintStart_toStartOf=“parent”/>
<ImageView
android:id="@+id/imageView"
android:layout_width=“256dp”
android:layout_height=“256dp”
android:layout_centerInParent=“true”
app:layout_constraintBottom_toBottomOf=“parent”</