首页 > 解决方案 > 片段中的 registerForActivityResult

问题描述

我试图registerForActivityResult在片段内部调用,当它完成时它只是关闭片段。

我的问题是如何从片段中调用此函数?

代码:

private val profileImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result != null && result.resultCode == Activity.RESULT_OK) {
        profileImageUri = result.data?.data

        try {
            profileImageUri?.let { profileImageUri ->
               if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P){
                    val bitmap: Bitmap = getBitmap(activity?.contentResolver, profileImageUri)

                    context?.let { context ->
                        Glide.with(context).load(bitmap).into(pfpIV)
                        // here it closes the fragment
                    }
                } else {
                    context?.let { context ->
                        val source = ImageDecoder.createSource(context.contentResolver, profileImageUri)
                        var bitmap = ImageDecoder.decodeBitmap(source)
                        bitmap =  bitmap.copy(Bitmap.Config.ARGB_8888, true)
                        Glide.with(context).load(bitmap).into(pfpIV)
                        // here it closes the fragment
                    }
                }
            }
        } catch (e:IOException){
            e.printStackTrace()
        }
    }
}

标签: androidandroid-studiokotlin

解决方案


那么我找到的唯一解决方案是使用一个活动,似乎在使用registerForActivityResult它时我会返回活动,而不是片段,所以如果你在一个不是活动主要/默认的片段中,你将无法要返回它,该函数会将您返回到活动的主要片段,因为它在技术上打开了一个新意图以从用户那里获取信息(在这种情况下为图像),因此它必须返回活动并且不能返回片段。


推荐阅读