kotlin onActivityResult()“意外覆盖”错误

niknxzdl  于 2022-11-16  发布在  Kotlin
关注(0)|答案(2)|浏览(172)

所以我正在制作这个应用程序,它可以捕捉一张图像,然后这个图像被进一步用来从中提取文本。我找到了这个代码,来访问相机和捕捉图像(在一个片段中):

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888
    var button: Button? = null
    var imageView: ImageView? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        button!!.setOnClickListener {
            fun onClick(view: View?) {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(
                    intent,
                    CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
                )
            }
        }
        return root
    }
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val bmp = data.extras!!["data"] as Bitmap?
                val stream = ByteArrayOutputStream()
                bmp!!.compress(Bitmap.CompressFormat.PNG, 100, stream)
                val byteArray: ByteArray = stream.toByteArray()

                // convert byte array to Bitmap
                val bitmap = BitmapFactory.decodeByteArray(
                    byteArray, 0,
                    byteArray.size
                )
                imageView!!.setImageBitmap(bitmap)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

但是onActivityResult()方法有一个“意外覆盖”错误,我不知道如何修复:

我试着将它添加到MainActivity类中,希望能达到最好的效果:

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

但这似乎没有帮助。我是一个完全的初学者,但我必须使这个应用程序真实的快速,所以将感谢任何建议或解释。
upd:我也尝试过添加关键字override,但是我得到错误“onActivityResult()overrides nothing”

nvbavucw

nvbavucw1#

必须覆盖onActivityResult函数,如onCreateViewonDestroyView。因此,只需在fun onActivityResult()左侧添加override关键字

8zzbczxx

8zzbczxx2#

您对OnActivityResult()的定义不正确。它需要与您尝试覆写的方法具有相同的签章。您需要:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

您需要在Intent?类型的最后一个参数上使用问号,因为此参数的值可能是null。这将与您尝试覆盖的Fragment中的方法的签名相匹配。

相关问题