android Zxing在fragment中使用(kotlin)
在build.gradle中添加依赖implementation 'com.google.zxing:core:3.3.3'implementation('com.journeyapps:zxing-android-embedded:3.6.0') { transitive = false }在fragment调用扫码代码中写入//注意:在fragment中调用要使用forSupportFragm
·
在build.gradle中添加依赖
implementation 'com.google.zxing:core:3.3.3'
implementation('com.journeyapps:zxing-android-embedded:3.6.0') { transitive = false }
在fragment调用扫码代码中写入
//注意:在fragment中调用要使用forSupportFragment(this)方式
val integrator = IntentIntegrator.forSupportFragment(this)
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES)
integrator.captureActivity = CaptureActivity::class.java
integrator.setRequestCode(_scan) //_scan为自己定义的请求码
integrator.initiateScan()
接收扫码结果
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode)
{
//_scan为自己定义的扫码请求码
_scan->{
// 跳转扫描页面返回扫描数据
var scanResult = IntentIntegrator.parseActivityResult(resultCode, data);//(IntentIntegrator.REQUEST_CODE, resultCode, data);
// 判断返回值是否为空
if (scanResult != null) {
//返回条形码数据
var result = scanResult.contents
binding.etxtbarcode.setText(result)
//AppContext.getContext()为自定义获取全局Context方法
Toast.makeText(AppContext.getContext(),"扫到条码:"+result,Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(AppContext.getContext(),"扫描失败",Toast.LENGTH_SHORT).show()
}
}
}
}
特别注意:
接收结果段中代码
var scanResult = IntentIntegrator.parseActivityResult(resultCode, data);
//(IntentIntegrator.REQUEST_CODE, resultCode, data);
此处requestCode不是之前自定义的_scan请求码,而是IntentIntegrator.REQUEST_CODE,或者把请求码参数取消不填,否则获取不到scanResult,即scanResult=null
参考:
解决zxing的IntentIntegrator在使用setRequestCode时获取不到结果的问题丶Java教程网-IT开发者们的技术天堂 (liangzl.com)
ZXing使用文章收藏:
更多推荐
已为社区贡献4条内容
所有评论(0)