官方文档说:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
但是,我看到多篇文章讨论使用 setTargetFragment() 将数据从 DialogFragment 发送到调用者 fragment 。
这对我来说似乎是一种反模式,因为它最大限度地减少了完成一项 Activity 的需要。
谁能解释一下引入 setTargetFragment() 和 getTargetFragment() 背后的原因?
最佳答案
架构并不总是 100% 干净。像 Android 这样大的东西是由几十个开发人员编写的,每个人都有自己的观点。有时这些点不同,有时会出现在未怀疑的 API 调用现有或文档不匹配中。
此外,兄弟 fragment 和子 fragment 之间也存在差异。一个 fragment 不应该知道任何关于它的 sibling 的信息。但是,如果一个 fragment 需要启动另一个 fragment 并处理它的结果(就像它可能是一个 Activity 一样),那么 fragment 直接执行它而不需要涉及它的 Activity 是完全可以接受的。这就是 setTargetFragment 的用途。
关于android - 为什么 Android 有 setTargetFragment() 用于从 DialogFragments 传回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664143/