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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With