Activity And Fragment Interaction

前端 未结 7 1250
南旧
南旧 2020-12-10 12:54

I have an Activity with multiple Fragments. I want to show a DialogFragment or open another Fragment from one of the

相关标签:
7条回答
  • 2020-12-10 13:46

    Personally I would say that fragments should be thought as reusable and modular components. So in order to provide this re-usability, fragments shouldn't know much about their parent activities. But in return activities must know about fragments they are holding.

    So, the first option should never be considered in my opinion for the dependency reason you mentioned causing a very highly coupled code.

    About the second option, fragments may delegate any application flow or UI related decisions (showing a new fragment, deciding what to do when a fragment specific event is triggered etc..) to their parent activities. So your listeners/callbacks should be fragment specific and thus they should be declared in fragments. And the activities holding these fragments should implement these interfaces and decide what to do.

    So for me the third option makes more sense. I believe that activities are more readable in terms of what they are holding and doing on specific callbacks. But yes you are right your activity might become a god object.

    Maybe you can check Square's Otto project if you don't want to implement several interfaces. It's basically an event bus.

    0 讨论(0)
提交回复
热议问题