T
T
terminator-light2019-05-09 21:33:58
Java
terminator-light, 2019-05-09 21:33:58

Which is better: getActivity() or onAttach(Context) in fragments?

You can get a link to an activity in fragments in these ways: by calling getActivity() or onAttach(Context) and casting it to Activity.
Why is it recommended to use the 2nd method instead of the first? Is there any snag?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-05-11
@zagayevskiy

terminator-light , you think I'm asking out of curiosity? It's not clear to me how you can even compare a callback and an access method. In the callback, the activity becomes available to you for the first time, if you need to do something at the same time, you do it in this callback. If in the future you need an activity, you get it from getActivity. At the same time, if you take and save the link in the callback, it will be wrong, up to memory leaks in a bad scenario (for example, if you do setRetainInstance (true)).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question