I know that there are many contexts in android like those
- Application
- Activity
- Service
- ContentProvider
- BroadcastReceiver
So when I create a new TextView
i have to pass the context
in the constructor like this
TextView textView = new TextView(this);
I know it is needed BUT why not just be created and android handle the context for me ?
I like to think of
context
visually, as I'm an avid user ofFragments
so most of the time I pass acontext
, or inherit acontext
instance it would generally be from anActivity
.as described on Android Developers. It basically gives you a help in hand from ensuring you can perform "up-calls for application-level operations", so let's detail this into your case.
The new instance of your
TextView
, when created without aContext
instance. So it'll look something likeTextView tv = new TextView();
will confuse Android in regards to where thatTextView
is being generated. How will they know if this is application level or activity level? what characteristics would theTextView
need before an instance is created? when you head over to theTextView
's constructor you'll notice how it'll need some vital information before it generates a new instance of saidTextView
. For example:final Resources.Theme theme = context.getTheme();
is just one line where they gather information through theContext
instance, now they know where the information is coming from, they can then apply the corresponding theme.How will Android know where you have called that class from and what theme you would like to be applied to it unless you have told them?
Finally to answer your question, "why not just be created android handle the context for me?" this IS android handling things for you, but it needs to know where you're coming from and where in the life-cycle you're at.
Edit: added from comments.
because again it boils down to where you want that widget to be based. So let's say I want a
TextView
inside of myactivity
but we're calling the application level context, the theme that would be applied automatically would be@style/apptheme
. But if I want thatTextView
to follow the same style guidelines at the currentactivity
, instead of manually changing the theme for every widget I want to create (me the developer) android handles it for you, regardless of where you are in the app. it makes styles simpler, creating new instances of theTextView
simple etc etcUnfortunately I have no experience to say with .NET but i think in regards to the ever changing state of activities, services and receivers during the use of an application which could be closed and opened at anytime. It's a nice feature being able ensure Android knows where you're at, and what you're creating.