I have a question about how to communicate between Activity and Fragment.

Asked 2 years ago, Updated 2 years ago, 51 views

Until recently, I had been implementing Fragment without much thought, but recently I have a sudden interest in it, so I have some questions.

In general, I understand that Fragments avoid accessing the variables or methods of Activity to implement them independently. Do you mean the parent activity right above here?

I understood the content above, but did you understand it correctly? Then, when implementing fragments that are not used in various activities, is it normal to implement them without following the above rules?

Conversely, is there a rule for approaching Fragment from Activity? For example, I have approached Fragment by implementing getter/setter. Please let me know if this is the right way or not, or if there is a better way.

Thank you.

android fragment

2022-09-22 16:56

1 Answers

Direct access using Getter/Setter is not a good way to have a dependency between Activity and Fragment.

In this case, Android examples usually use Interface.

If Fragment needs to know any changes in Activity, Create an interface, implement the interface in Fragment, and call from Activity.

If Activity needs to know the action of Fragment, on the other hand, you can implement the interface in Activity and deliver it to Activity through the interface in Fragment.

Because both Activity and Fragment are designed to be invoked and used here and there, depending on a particular activity or fragment, maintenance will be difficult later, and it may be difficult to know where the value was changed during debugging.

We recommend using Interface.

+@ Another way is the event bus method, but I personally don't recommend it. (It's easier to develop, but it's much harder to track and debug the code.)


2022-09-22 16:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.