为什么我的扫描码显示为“未使用”?

问题描述 投票:0回答:1

我有一个带有两个按钮和一个数据输入字段的单屏应用程序。我正在尝试对数据字段实现条形码扫描,但不清楚扫描仪代码应该放在哪里,因为 Scanner 实例显示为“未使用”。

如何使实例对我的 clickToScan 函数可见?

package com.example.mngv3
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.google.mlkit.vision.barcode.common.Barcode
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.mlkit.vision.codescanner.GmsBarcodeScanner
import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions
import com.google.mlkit.vision.codescanner.GmsBarcodeScanning

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    // Not sure where this code should go???
    // Establish scan symbologies
    val options = GmsBarcodeScannerOptions.Builder()
        .setBarcodeFormats(
            Barcode.FORMAT_CODE_39,
            Barcode.FORMAT_CODE_128,
            Barcode.FORMAT_QR_CODE,
            Barcode.FORMAT_DATA_MATRIX
        )
        .build()
    // Next "scanner" shows as unused???
    // Establish scanner instance
    val scanner = GmsBarcodeScanning.getClient(this,options)

    fun clickToScan(view: View,scanner: GmsBarcodeScanner) {
        // This function is triggered by onClick in activity_main.xmlScan button
        scanner.startScan()
            .addOnSuccessListener { barcode ->
                // Task completed successfully
                val result = barcode.rawValue
                return@addOnSuccessListener Toast.makeText(this, result, Toast.LENGTH_LONG)
                    .show()
            }
            .addOnFailureListener {
                // Task failed with an exception
                return@addOnFailureListener Toast.makeText(
                    this,"Scanning failed!", Toast.LENGTH_LONG)
                    .show()
            }
    }

}

enter image description here

android xml kotlin
1个回答
0
投票

您的方法

clickToScan
还采用参数
scanner
并使用它来代替您的班级范围内的
scanner
。如果您想使用“未使用”的,您可以通过写
this.scanner.startScan()
来指定。

© www.soinside.com 2019 - 2024. All rights reserved.