Reputation: 463
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
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
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
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:
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