O
O
orbit0702019-07-29 19:01:48
Android
orbit070, 2019-07-29 19:01:48

How bad is it to call the activity method from the fragment directly?

There is an activity that defines the "Open screen X" method.
This method is defined in the activity, and not in the fragment, based on the fact that it must be called with a certain intent (that is, I intercept the intent in onNewIntent and call this method).
There is also a scenario where I need to open the same X screen by clicking on a button in one of the fragments. In order not to duplicate the code of the "Open screen X" method from the activity to the fragment, it seems logical to call this method from the fragment.
Here, in fact, the question is: is it necessary to fence the interface with a callback in order to inform the activity from the fragment about the need to call this method, or can you just execute ((MyActivity) GetActivity()).openScreenX() ? How bad is it to do so and what is fraught with? Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2019-07-29
@orbit070

I don’t see anything wrong with this if the fragment is in the FragmentManager activty and you stick to the standard android MVC, but you need to understand that at different stages of the fragment’s life, the getActivity () method can return both a reference to the activity and null.

T
tiroman, 2019-07-30
@tiroman

You can use the EventBus library and communicate between application components with events, the connectivity between them is reduced, it doesn’t matter if it’s a fragment and an activity, or some kind of background service and the same activity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question