为什么 Android 有 setTargetFragment() 用于从 DialogFragments 传回数据?
Why does Android have setTargetFragment() for communicating data back from DialogFragments?
官方文档说:
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 发送到调用者片段。
这对我来说似乎是一种反模式,因为这最大限度地减少了 activity 的需要。
谁能解释一下引入 setTargetFragment() 和 getTargetFragment() 的原因?
架构并不总是 100% 干净。 Android 这么大的东西是由几十个开发人员编写的,每个人都有自己的观点。有时这些点不同,有时会出现在未预料到的 API 现有调用或文档不匹配中。
此外,兄弟片段和子片段之间存在差异。一个片段不应该知道任何关于它的兄弟姐妹的信息。但是如果一个片段需要启动另一个片段并处理它的结果(就像它可能是一个 activity)那么片段直接完成它是完全可以接受的,而不需要涉及它的 activity。这就是 setTargetFragment 的用途。
官方文档说:
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 发送到调用者片段。
这对我来说似乎是一种反模式,因为这最大限度地减少了 activity 的需要。
谁能解释一下引入 setTargetFragment() 和 getTargetFragment() 的原因?
架构并不总是 100% 干净。 Android 这么大的东西是由几十个开发人员编写的,每个人都有自己的观点。有时这些点不同,有时会出现在未预料到的 API 现有调用或文档不匹配中。
此外,兄弟片段和子片段之间存在差异。一个片段不应该知道任何关于它的兄弟姐妹的信息。但是如果一个片段需要启动另一个片段并处理它的结果(就像它可能是一个 activity)那么片段直接完成它是完全可以接受的,而不需要涉及它的 activity。这就是 setTargetFragment 的用途。