Fragment-to-Fragment communication 的麻烦之处

前端之家收集整理的这篇文章主要介绍了Fragment-to-Fragment communication 的麻烦之处前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天要做一个从 Fragment 调出一个 DialogFragment 的效果,其中从 DialogFragment 的 Callback 本来是 Activity 中很好写,拿到了 Fragment 里发现很麻烦,不知道该怎么注册这个监听器。然后发现有人问了同样的问题。

里面有人用比较麻烦的方法实现了效果,但是看到一个回答说出了为什么这么麻烦的原因——因为根本不建议这么写:

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.

然后就有人评论说:

I think that as the uses of fragments has been expanded the original idea of not using direct fragment communication breaks down. E.g. in a navigation drawer each immediate child fragment of the activity is roughly acting as an activity. So having a fragment such as a dialogfragment communicate through the activity harms readability/flexibility IMO. In fact there doesn't seem to be any nice way to encapsulate dialogfragment to allow it to work with both activities and fragments in a reusable way.

I know this is old,but in case anyone else comes here I feel like the case talked about in that document doesn't apply when one fragment "owns" the logic that is used to determine creation and management of the DialogFragment. Its kind of weird to create a bunch of connections from the fragment to the activity when the activity isn't even sure why a Dialog is being created or under what conditions it should be dismissed. Besides that the DialogFragment is super simple,and exists only to notify the user and potentially get a response.

觉得说得有道理,希望 Google 下次能够把这件事情变得更加简单。那现在只能先用其他的办法了。

原文链接:https://www.f2er.com/note/421755.html

猜你在找的程序笔记相关文章