vadim
vadim

Reputation: 175

How a Fragment can be associated with a Context?

In the documentation of the android.support.v4.app.Fragment class (not the framework's class) for the getActivity() method stated that the returned value may be null if the Fragment is associated with a Context.

How an Fragment can be associated with a Context? Is not the FragmentManager the only way to attach an Fragment to something? But the FragmentManager can be obtained only from Activity. Or not?

Upvotes: 9

Views: 1336

Answers (2)

Paresh
Paresh

Reputation: 6857

How an Fragment can be associated with a Context?

You must have heard of FragmentHostCallback. If you haven't check out the link.

In a simple way, it is an integration point with a Fragment Host. When I say Fragment Host, It is an object that can hold Fragments. For example an Activity. In order to host a fragment - one must implement FragmentHostCallback.

However, I haven't come up with any ideas about how Fragment can be implemented in non-activity objects. Will see in future may be...

So that way, getActivity() will return null on non-activity objects.

PS,
Always go for getContext() if you are requiring context rather than activity

Upvotes: 6

DPE
DPE

Reputation: 228

As I understand, you need the context inside of a fragment.. If so have you checked the method getContext() method inside of a fragment?

Also getActivity() can be null if you are referencing it when the fragment is not attached to an activity. Have a check of the fragment lifecycle to learn more.

Hope I helped

Upvotes: 1

Related Questions