Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between getContext of Fragment and getContext of container passed to onCreateView of Fragment?

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)

Say if we call

fragment.getContext() and container.getContext will we get same result, the host activity?

Also does view.getContext() always returns Activity context or can it return some other kind of context?

like image 527
q126y Avatar asked Oct 29 '22 23:10

q126y


1 Answers

Activity class in android extends Context class. So basically an activity is a context. But a context may not be an activity.

fragment.getContext() will return context of the container it is attached to. So yes container.getContext() will have the same results as of fragment.getContext() ie., the host activity.

When instance of the ViewGroup is created, the inflater pass context of that activity to it. Means container.getContext() will return that same context.

fragment.getActivity() will return an activity it is attached with which is again a context. When the fragment is detached from the activity, it returns null. And when attached it also returns same as getContext()

And about your last question, view.getContext() returns context in which it is running. View doesnt extend Context class, infact when they are created, they require context object as parameter. So when you are creating a View inside a activty, you need to pass Context. And when you you call view.getContext(), you will get the same context back which you passed when you created it.

like image 74
Dinesh Choudhary Avatar answered Nov 15 '22 06:11

Dinesh Choudhary