Android Kotlin 从 Activity 中获取 Fragment 中的 Zxing 条码结果

标签 android kotlin android-fragments zxing

使用 Android Studio Kotlin,我在应用程序中使用 Zxing 条形码扫描仪。我的应用程序使用 fragment 架构。我可以从 fragment 中扫描我的应用程序中的条形码,但扫描结果将返回到 Activity 中。我相信是故意的,因为签名需要 Activity 作为输入。

我的问题是, a) 如何从 fragment 调用中获取扫描的返回值以在 fragment 中而不是在 Activity 中执行 onActivityResult ? 或者 b) 获取 Activity 接收到的结果并传回 fragment ?

我正在使用以下教程 Barcode Scanning in Kotlin

以下java based post说要覆盖该函数,但这似乎并没有实际覆盖父函数,因为扫描仪函数签名似乎引用了该 Activity 。

更新说明:

我更改了代码以使用 nav_graph。如果不使用 nav_graph,我会收到找不到 fragment 警告。

Log.d 结果显示 MainActivity 函数被调用。

barcoderead D/MainActivity: Format: UPC_A
    Contents: 630509790043

list 添加

    <uses-feature android:name="android.hardware.camera.autoFocus" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

build.gradle(应用程序)添加

    implementation 'com.google.zxing:core:3.3.3'
    implementation 'com.journeyapps:zxing-android-embedded:3.2.0'

主要 Activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.Navigation
import com.google.android.gms.ads.MobileAds
import com.google.zxing.integration.android.IntentIntegrator
import com.lightningbraingames.mytoybox.R

class MainActivity : AppCompatActivity() {

    lateinit var btnBarcode: Button
    lateinit var textView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Navigation.findNavController(this,
            R.id.nav_host_fragment
        )

    }
}

fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.google.zxing.integration.android.IntentIntegrator

class BarcodeRead : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_barcode_read, container, false)
    }

    lateinit var btnBarcode: Button
    lateinit var textView: TextView

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btnBarcode = view.findViewById(R.id.button)
        textView = view.findViewById(R.id.txtContent)
        btnBarcode.setOnClickListener {
            val intentIntegrator = IntentIntegrator(activity)
            intentIntegrator.setBeepEnabled(false)
            intentIntegrator.setCameraId(0)
            intentIntegrator.setPrompt("SCAN")
            intentIntegrator.setBarcodeImageEnabled(false)
            intentIntegrator.initiateScan()
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(context, "cancelled", Toast.LENGTH_SHORT).show()
            } else {
                Log.d("Fragment", "Scanned from Fragment")
                Toast.makeText(context, "Scanned -> " + result.contents, Toast.LENGTH_SHORT)
                    .show()
                textView.text = String.format("Scanned Result: %s", result)
                Log.d("Fragment", "$result")
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

布局 主要 Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"/>

</LinearLayout>

fragment

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:padding="8dp"
        android:text="Tutorials Point"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="48sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/txtContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button"
        android:layout_centerInParent="true"
        android:layout_marginBottom="10dp"
        android:text=" code reader"
        android:textSize="16sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp"
        android:text="Process" />
</RelativeLayout>

最佳答案

如果您的问题是您的 fragment 没有获得结果,则可能您在基于 ZXing Documentation 的 fragment 中丢失了某些内容。 :

从你的 Activity 中应该

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

来自您的 fragment BarcodeRead

//val intentIntegrator = IntentIntegrator(activity)
val intentIntegrator = IntentIntegrator.forSupportFragment(this) // use this instead

使用 IntentIntegrator.forSupportFragment() 而不是 IntentIntegrator(getActivity()) 非常重要,因为如果使用后者,结果将仅在 Activity 页面。

关于Android Kotlin 从 Activity 中获取 Fragment 中的 Zxing 条码结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65694694/

相关文章:

android - 无法将空值注入(inject)类

c# - 多个客户端使用 Active Directory 进行身份验证

Android高分辨率图像处理

kotlin - 如何从命令行运行 Kotlin 类?

Kotlin 方法在执行任何条件 block 后执行操作

flutter - 从 2.8.1 升级到 Flutter 3.0,得到 : Warning: Operand of null-aware operation '?.' has type 'PaintingBinding' which excludes null error

android - 无法在 Android Studio 中更改 SDK 路径

android - 有没有在前面部分有NFC阅读器的android手机/设备

android - ListView自定义背景色

java - findViewById 在 Fragment 而不是在 (On)CreateView