Context Vs Views
Solution 1:
This is a strange question. View describes one element of your ui. It can have onClickListeners, properties and so on. But every view is created in some context, usually Activity's context.
Context as itself is something like environment your code is executed in. It has access to ui(if it is an activity), it can contain some global data(application context), and has access to the resources(all of the contexts). Also, context allows you to perform common android operations like broadcasting intents, start activities and services.
So, views should be passed when you want to do something with a particular view. Context is passed when you need access to resources, global data or ui context, or launch other android components.
Solution 2:
We need to understand how View
is constructed and what is Context
.
View
has three constructors, all of which use Context
as an argument.
In Activity,
if view
is inflated programmatically as against in XML, view
is inflated a View
is by using LayoutInflater
.
LayoutInflater
takes Context
as an argument and internally saves it in a class level field.
LayoutInfater layoutinflater = LayoutInflater.from(this);
where "this
" is the Activity
instance.
When inflater
inflates view i.e. :
inflater.inflate(R.id.some_view, parent, null)
,
it is internally passing the saved context
field to the constructor of View
.
View
always takes a Context
as an argument and this is obvious because views live in some Context
which is the Activity
.
To answer your question, when context
is needed to be passed to a method which itself is in Activity
, you can write "this
". If method is not in Activity
, and you need to pass Context
, then remember that View
which has taken Context
as a parameter, saves the object reference in a class level field. We can get this object reference by writing view.getContext()
.
Post a Comment for "Context Vs Views"