没有调用onActivityResult(Kotlin)

时间:2017-07-28 09:10:30

标签: android kotlin onactivityresult

我需要帮助。在我的onCreate()我有这段代码:

    takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
        setListener(object : DialogGetPhotoFrom.DialogListener {
            override fun onTakeFromGallery() {
                Log.v("ProjectDetails", "onTakeFromGallery called")
                val intent = Intent().apply {
                    type = "image/*"
                    action = Intent.ACTION_GET_CONTENT
                }
                startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
            }

            override fun onTakePhoto() {
                dispatchTakePictureIntent()
            }
        })
    }

    projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }

在我的onActivityResult上,我写道:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PICK_IMAGE -> {
            Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    try {
                        val inputStream = contentResolver.openInputStream(data.data)
                        val bitMap = BitmapFactory.decodeStream(inputStream)
                        projectDetails_image.setImageBitmap(bitMap)
                        // TODO Save image URI to database
                    } catch (e: Exception) {
                        Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Log.v("ProjectDetails", "data is null")
                }
            }
        }
    }
}

问题是,onActivityResult()在选择图像时不会触发。我该怎么办?

1 个答案:

答案 0 :(得分:1)

解决了!解决方案是将我的onTakeGallery()函数中的代码放到属于Activity类的函数中。所以我的代码看起来像这样:

takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
    setListener(object : DialogGetPhotoFrom.DialogListener {
        override fun onTakeFromGallery() {
            dispatchSelectFromGalleryIntent()
        }

        override fun onTakePhoto() {
            dispatchTakePictureIntent()
        }
    })
}

projectDetails_pickImage.setOnClickListener { 
    takePhotoDialog?.show(supportFragmentManager)
}

提取的代码在这里:

private fun dispatchSelectFromGalleryIntent() {
    val intent = Intent().apply {
        type = "image/*"
        action = Intent.ACTION_GET_CONTENT
    }
    startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}