英文:
Send result from DialogFragment to Fragment
问题
在对话中,我使用下面的扩展来发送结果:
fun <T : Any> Fragment.setNavigationResult(
result: T, key: String,
navController: NavController = findNavController()
) {
navController.previousBackStackEntry?.savedStateHandle?.set(key, result)
}
在片段中获取结果的代码如下:
fun <T> Fragment.getNavigationResult(@IdRes id: Int, key: String, onResult: (result: T) -> Unit) {
val navBackStackEntry = findNavController().getBackStackEntry(id)
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && navBackStackEntry.savedStateHandle.contains(key)) {
val result = navBackStackEntry.savedStateHandle.get<T>(key)
result?.let(onResult)
navBackStackEntry.savedStateHandle.remove<T>(key)
}
}
navBackStackEntry.lifecycle.addObserver(observer)
viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_DESTROY) {
navBackStackEntry.lifecycle.removeObserver(observer)
}
})
}
但我遇到了这样的崩溃问题。你知道如何修复吗?
Note: I've provided the translated code and information as requested. If you have any specific questions or need further assistance, please feel free to ask.
英文:
In dialog I use next extension to send result
fun <T : Any> Fragment.setNavigationResult(
result: T, key: String,
navController: NavController = findNavController()
) {
navController.previousBackStackEntry?.savedStateHandle?.set(key, result)
}
in fragment to get result
fun <T>Fragment.getNavigationResult(@IdRes id: Int, key: String, onResult: (result: T) -> Unit) {
val navBackStackEntry = findNavController().getBackStackEntry(id)
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && navBackStackEntry.savedStateHandle.contains(key)) {
val result = navBackStackEntry.savedStateHandle.get<T>(key)
result?.let(onResult)
navBackStackEntry.savedStateHandle.remove<T>(key)
}
}
navBackStackEntry.lifecycle.addObserver(observer)
viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_DESTROY) {
navBackStackEntry.lifecycle.removeObserver(observer)
}
})
}
Somebody know how to fix this?
答案1
得分: 1
以下是翻译好的部分:
有一种使用 fragmentManager
而不是 backstackEntry
的 Fragment 的本地解决方案。
请查看这里:https://developer.android.com/guide/fragments/communicate#fragment-result
英文:
There is a native solution of Fragment which uses fragmentManager
instead of backstackEntry
.
Please check here: https://developer.android.com/guide/fragments/communicate#fragment-result
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论