Each Activity is a Context. Each View needs a Context. Is it correct to say that when we pass the Context to a View, we are basically adding a View to a certain Activity by passing the Context?
1 Answers
The context is required because it provides access to many android system resources.
It provides theme information so that the view can properly draw itself with the given theme, but also provides a way to access other types of resource.
It provides access to layout inflater which may be needed to create child views.
You can use context to access String resources (and other resources). You may need Strings to add an appropriate text label to your view.
If you need access to shared preferences, that can be accessed via a context.
It is not correct to say that you are adding a view to an activity if you have passed that activity to the view as a context. The activity is simply providing the context needed by the view.
Here is a more thorough answer explaining the purpose of a context
-
2I completely understand that the context provides access to many resources. But, I remember when I started learning Java and doing stuff with `jFrame` and `jPanel` etc., I didn't need to pass a context to a `jButton`, I just did `jPanel.add(jButton)`. So why we pass `Context` in Android programming? There must be something that the `Context` does or is apart from providing access to system resources. Any help? – imran.razak May 02 '17 at 08:56
-
I'm not sure I can add much more to this answer that has not already been covered in the question that I linked. If you want take a closer look, you can always read through [the source](https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/Context.java). I have not used Swing before, but that is a different framework with different design considerations, and I am sure there are good reasons that they were architected differently. – Stephen May 02 '17 at 14:43