registerForActivityResult in fragment



我试图在片段内调用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()
}
}
}

好吧,我发现唯一的解决方案是使用一个活动,似乎当使用registerForActivityResult它返回我的活动,而不是片段,所以如果你是在一个片段,不是活动的主/默认你将无法返回到它,该功能将返回到主片段的活动,因为它在技术上打开一个新的意图从用户(图像在这种情况下)获取信息,因此,它必须返回到活动,而不能返回到片段。

最新更新