Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 482
vadim Avatar asked Feb 02 '18 09:02

vadim


1 Answers

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

like image 59
Paresh P. Avatar answered Oct 06 '22 01:10

Paresh P.