android - 片段中的 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()
}
}
}
解决方案
那么我找到的唯一解决方案是使用一个活动,似乎在使用registerForActivityResult
它时我会返回活动,而不是片段,所以如果你在一个不是活动主要/默认的片段中,你将无法要返回它,该函数会将您返回到活动的主要片段,因为它在技术上打开了一个新意图以从用户那里获取信息(在这种情况下为图像),因此它必须返回活动并且不能返回片段。
推荐阅读
- node.js - 云函数中的 QueryDocumentSnapshot 中不存在 data() 方法
- python - ValueError:“标签”的长度必须为“x”
- log4j - 如何在控制台中显示 extentReports 日志详细信息
- angular - 无法通过本地 ionic 应用程序连接到 azure iot hub
- oracle - 从交互式报告中的列中选择行值
- reactjs - 使用未声明的别名导入 React Typescript 组件
- python - 在 Ubuntu 16.04 (AWS EC2) 上损坏了 python 依赖项
- c++ - 如何使用 ISpLexicon::GetWords 获取单词列表?
- python - 用“with语句”关闭psyopg2中的连接的正确方法是什么?
- c# - 如何从列表中删除生成的标签