如何在Android StudioKotlin中扫描图像QR后将数据显示到TextBox

ctzwtxfj  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(169)

我正在扫描图像,当数据被扫描时,我希望将其传输或显示到TextBox。
我所做的是扫描它,并试图显示它的文本框,但它不会显示文本。
我的结果是,文本框不显示QR扫描的任何数据。
编码:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if(resultCode  == Activity.RESULT_OK){
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null)
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show()
            else {
                try {
                    // Display this to Textbox
                    val decryptedText = EncryptDecrypt.decrypt(decryptET.text.toString())
                    encryptET.setText(decryptedText)
                } catch (e: InvalidAlgorithmParameterException) {
                    e.printStackTrace()
                } catch (e: NoSuchPaddingException) {
                    e.printStackTrace()
                } catch (e: IllegalBlockSizeException) {
                    e.printStackTrace()
                } catch (e: NoSuchAlgorithmException) {
                    e.printStackTrace()
                } catch (e: BadPaddingException) {
                    e.printStackTrace()
                } catch (e: InvalidKeyException) {
                    e.printStackTrace()
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}
gcuhipw9

gcuhipw91#

对于这个案例,我推荐这个图书馆。
程式库-实作'com.budiyev.android:程式码扫描器:2.1.0'
在Xml中添加扫描器视图

<com.budiyev.android.codescanner.CodeScannerView
    android:id="@+id/qr_scanner"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是活动或片段代码获取权限并扫描Qr图像示例

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
private lateinit var codeScanner: CodeScanner

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    codeScanner = CodeScanner(this, binding.qrScanner)


    if (allPermissionsGranted()) {
        codeScanner.startPreview()
    } else {
        permissionLauncher.launch(Manifest.permission.CAMERA)
    }

    codeScanner.decodeCallback = DecodeCallback {
        runOnUiThread {
            //Get text it.text and put in TextBox
            println(it.text)
        }
    }
}

private fun allPermissionsGranted() = arrayOf(Manifest.permission.CAMERA).all {
    ContextCompat.checkSelfPermission(
        this, it
    ) == PackageManager.PERMISSION_GRANTED
}

private val permissionLauncher =
    registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (allPermissionsGranted()) {
            codeScanner.startPreview()
        } else {
            finish()
        }
    }

相关问题