Diego Perdomo
Diego Perdomo

Reputation: 463

Manually setting context in Android

I am new to Android development and I made a research about Context. I understand what it is and why is usefull. But I see that android handles context for me in activities for example, I have to extends a class that inherits from context and thats it. However in some situations I have to manually add context to a thing. For example when creating a new instance of a view from kotlin. I have to pass a context to the view constructor, for example: Button(this)

Why do I have to tell a view instance that it is part of an activity explicitly?

I am defining it inside the activity after all.

I understand that context it's like a bridge between my app and external resources and system tools but setting it manually sometimes confuses me.

Upvotes: 2

Views: 1021

Answers (3)

Gourav
Gourav

Reputation: 2819

This is because there can many other parameters for this.

We set the context because we let the Button base class(or any other you're using) that the declared variable is instance of Button but not the other classes available all over!

Upvotes: 1

Diego Perdomo
Diego Perdomo

Reputation: 463

I found this article: https://www.101apps.co.za/index.php/articles/all-about-using-android-s-context-class.html

I think that explains very well why do we need to pass context manually to view instances.

"Passing the context to the view when it is being constructed, gives you the flexibility to use a different context to construct the view, as the one used by the activity, for example. This gives the view access to resources other than those used by the activity."

Android could set context automatically but it gives you freedom to choose another one. That could be useful.

Upvotes: 1

Maneki Neko
Maneki Neko

Reputation: 1267

True, theoretically, that could have been done only when attaching the view to a parent, and then if the parent is attached to the activity root it has context, if not - when attaching a view, Android could have gone over its descendants and set their Context.

However:

  1. It is inconvenient to implement. It's easy to have autonomous views with each already set to its context.
  2. There are some things that are in the context and are necessary for manipulating the view. E.g. constraint system, metrics... many bits and bolts. Views also listen to events and can provide some services that require Context before they are attached to another view.
  3. What if you have several contexts. You want to be able to choose which context to refer to. Say, you got an always-on-too floating button that is managed by some service and views managed by the activity.

It is highly recommended to peek in Android sources. You will find cool facts inside, and it's an excellent way to learn.

Upvotes: 2

Related Questions