1.控件
1.1按钮
获取按钮:
Button btn_scan_view=(Button) findViewById(R.id.button_get);
按钮点击事件:
//点击开始生成按钮监听事件
btn_get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//点击事件内容
}
});
1.2 输入框
输入框:
EditText edittext=findViewById(R.id.editTextText);//输入框
获取输入内容:
String input= edittext.getText().toString();
1.3 图像
获取图像控件:
ImageView img_view=(ImageView)findViewById(R.id.imageView);
将图像填充到控件:
img_view.setImageBitmap();
2.页面跳转
2.1 跳转到自定义页面
使用Intent来实现页面跳转
首先,我们需要创建一个新的Android Activity。在Android Studio中,可以通过以下步骤实现:
在项目的结构视图中,右键点击app -> New -> Activity -> Blank Activity,然后给新的Activity命名并选择放在哪个文件夹下。
在AndroidManifest.xml文件中,我们需要为新的Activity注册一个类别。
//监听按钮,如果点击,就跳转
ntent intent = new Intent();
//前一个(MainActivity.this)是目前页面,后面一个是要跳转的下一个页面
intent.setClass(MainActivity.this,ScanActivity.class);//ScanActivity修改为待跳转页面
startActivity(intent);
3.代码示例(生成、扫描二维码)
3.1 创建项目及准备工作
创建项目修改镜像提速(settings.gradle.kts)文件修改为:
pluginManagement {
repositories {
maven { setUrl("https://maven.aliyun.com/repository/public") }
maven { setUrl("https://maven.aliyun.com/repository/central") }
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
maven { setUrl("https://maven.aliyun.com/repository/public") }
maven { setUrl("https://maven.aliyun.com/repository/central") }
google()
mavenCentral()
}
}
maven添加jar包,在build.gradle.kts添加:
implementation("com.journeyapps:zxing-android-embedded:3.6.0")
gradle下载版本:
https://services.gradle.org/distributions/
3.2 主页面(生成二维码):
代码:
package com.example.week08_or;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.util.Hashtable;
public class MainActivity extends AppCompatActivity {
Button btn_get;
Button btn_scan_view;
ImageView img_view;
EditText edittext;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_get=(Button) findViewById(R.id.button_get);
img_view=(ImageView)findViewById(R.id.imageView);
btn_scan_view=(Button)findViewById(R.id.button_page);//跳转页面
edittext =findViewById(R.id.editTextText);//输入框
//点击开始生成按钮监听事件
btn_get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input= edittext.getText().toString();
//调用CreateUtil类生成二维码后显示在界面上
img_view.setImageBitmap(createQRCode(input,img_view.getWidth(),img_view.getHeight()));
}
});
btn_scan_view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//监听按钮,如果点击,就跳转
Intent intent = new Intent();
//前一个(MainActivity.this)是目前页面,后面一个是要跳转的下一个页面
intent.setClass(MainActivity.this,ScanActivity.class);
startActivity(intent);
}
});
}
//将输入的字符串转为图像
public Bitmap createQRCode(String codestring, int width, int height){
try {
//首先判断参数的合法性,要求字符串内容不能为空或图片长宽必须大于0
if (TextUtils.isEmpty(codestring)||width<=0||height<=0){
return null;
}
//设置二维码的相关参数,生成BitMatrix(位矩阵)对象
Hashtable<EncodeHintType,String> hashtable=new Hashtable<>();
hashtable.put(EncodeHintType.CHARACTER_SET,"utf-8"); //设置字符转码格式
hashtable.put(EncodeHintType.ERROR_CORRECTION,"H"); //设置容错级别
hashtable.put(EncodeHintType.MARGIN,"2"); //设置空白边距
//encode需要抛出和处理异常
BitMatrix bitMatrix=new QRCodeWriter().encode(codestring, BarcodeFormat.QR_CODE,width,height,hashtable);
//再创建像素数组,并根据位矩阵为数组元素赋颜色值
int[] pixel=new int[width*width];
for (int h=0;h<height;h++){
for (int w=0;w<width;w++){
if (bitMatrix.get(w,h)){
pixel[h*width+w]= Color.BLACK; //设置黑色色块
}else{
pixel[h*width+w]=Color.WHITE; //设置白色色块
}
}
}
//创建bitmap对象
//根据像素数组设置Bitmap每个像素点的颜色值,之后返回Bitmap对象
Bitmap qrcodemap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
qrcodemap.setPixels(pixel,0,width,0,0,width,height);
return qrcodemap;
}catch (WriterException e){
return null;
}
}
}
layout文件:
<?xml version="1.0" encoding="utf-8"?>
<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">
<ImageView
android:id="@+id/imageView"
android:layout_width="301dp"
android:layout_height="283dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="149dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_get"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="@drawable/ic_launcher_background" />
<Button
android:id="@+id/button_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="21dp"
android:layout_marginBottom="529dp"
android:text="生成"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/button_page"
app:layout_constraintTop_toBottomOf="@+id/editTextText" />
<EditText
android:id="@+id/editTextText"
android:layout_width="355dp"
android:layout_height="78dp"
android:ems="10"
android:inputType="text"
android:text="输入需生成的字符串"
app:layout_constraintBottom_toTopOf="@+id/button_page"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button_page"
android:layout_width="108dp"
android:layout_height="59dp"
android:layout_marginStart="23dp"
android:text="扫码页面"
app:layout_constraintBaseline_toBaselineOf="@+id/button_get"
app:layout_constraintEnd_toStartOf="@+id/button_get"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.3 扫描二维码
代码:
package com.example.week08_or;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;
public class ScanActivity extends AppCompatActivity {
Button btn_scan;
Button btn_back;
TextView textView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);//绑定页面
btn_scan=(Button)findViewById(R.id.btn_scan);
btn_back=(Button) findViewById(R.id.button2);
textView=(TextView)findViewById(R.id.textView);
//扫描二维码按钮点击事件
btn_scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//.QR_CODE_TYPES 二维码
//ONE_D_CODE_TYPES条形码
//ALL_CODE_TYPES 所有类型
new IntentIntegrator(ScanActivity.this).setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选:一维码,二维码,一/二维码
.setPrompt("请对准二维码")// 设置提示语
.setCameraId(0)// 选择摄像头,可使用前置或者后置
.setBeepEnabled(false)// 是否开启声音,扫完码之后会"哔"的一声
//.setBarcodeImageEnabled(true)// 扫完码之后生成二维码的图片
.setCaptureActivity(CaptureActivity.class)
.initiateScan();// 初始化扫码
}
});
//返回上一页面
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
#回调函数,处理扫描结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
textView.setText(result.getContents());
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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">
<Button
android:id="@+id/btn_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="104dp"
android:layout_marginBottom="90dp"
android:text="扫描"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="55dp"
android:layout_marginEnd="55dp"
android:layout_marginBottom="275dp"
android:text="扫描结果"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_scan" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="33dp"
android:layout_marginTop="5dp"
android:text="返回"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/btn_scan" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.2.3 自定义扫描窗口
需要将
setCaptureActivity(CaptureActivity.class)
修改为:
setCaptureActivity(CustomCaptureActivity.class)
//CustomCaptureActivity为自定义activity名称。
Activity:
package com.example.week08_or;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.KeyEvent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
public class CustomCaptureActivity extends AppCompatActivity {
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_capture);// 自定义布局
barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.dbv_custom);
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
@Override
protected void onResume() {
super.onResume();
capture.onResume();
}
@Override
protected void onPause() {
super.onPause();
capture.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<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">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="@+id/dbv_custom"
android:layout_width="372dp"
android:layout_height="683dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:zxing_preview_scaling_strategy="fitXY"
tools:layout_editor_absoluteY="19dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>