Why we need to pass Context to a View? - android

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?

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

Related

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.
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 inconvenient to implement. It's easy to have autonomous views with each already set to its context.
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.
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.
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.
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!

does it guarantee to give same result in getDefaultSharedPreferences within Context?

I read this discussion but still have a question.
If I use getDefaultSharedPreferences(getApplicationContext()) and getDefaultSharedPreferences(SomeActivity.this), does it gurantee to give same result (same xml preference file access)?
yes it does. The context parameter is used to get the package name, that will be used as name for the xml file in which android stores your values. You can see the androis's source code here
Wishing you a happy new year-2014
Both will behave same !!
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().
Please Note that behind the scenes
getDefaultSharedPreferences(context)
calls
getSharedPreferences(context.getPackageName(), MODE_PRIVATE)
as far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context;
Hope now you understand the things so we can say that they will produce same behave.
Please refer http://developer.android.com/reference/android/app/Activity.html
and
http://developer.android.com/reference/android/content/Context.html

When will a View method's Context param not be equivalent to .getContext()

If you are able to call view.getContext() to return the Activity's context under which the view instance is currently being rendered, why do some of the View family methods take a Context as a parameter?
Could this not be implicit, or are there occassions when getContext() is different from a Context passed to one of these methods?
Here is an example: http://developer.android.com/reference/android/widget/ViewAnimator.html#setInAnimation(android.content.Context, int)
Many thanks for clearing this up
view.getContext() actually return's your Activity's context, not application's. That is the reason you need to provide such context when initializing a new View.
And there's a difference between these two contexts. An Activity's context is attached to that particular activity's life-cycle. However, the application's context is referring to application's life-cycle.
For more info, read this.
I recently read some API returning IBinder, like getWindowToken() and getApplicationWindowToken(). Quoting the latter:
Retrieve a unique token identifying the top-level "real" window of the
window that this view is attached to. That is, this is like
getWindowToken(), except if the window this view in is a panel window
(attached to another containing window), then the token of the
containing window is returned instead.
Maybe this IPC mechanism has something to do with the View API. Android designers are not stupid or zealous: if they require a Context to build a View, it means that a Context is all they need, so building a View must be possible with an application context, a service context and -of course!- an activity context, but an activity is not required. The Context is just an umbrella API to retrieve resources, accessing databases, building intents and the like.
This is not the answer to your question, but maybe can serve as a helper point. I'm looking for the answer myself. Hope your question gets the attention it deserves.

Can all views within an activity be assumed to have same Context?

I have noticed with Views in android that sometimes getContext() returns the containing activity, whilst other times it returns the application.
For the purposes of cleaning up pending remote image loads (which I am loading via an external load manager class), can I safely assume that all views on a particular Activity will share the same context? I was thinking of passing the activity object to cleanup and removing all views with a context matching that activity. I am sure it will depend on a few things to do with the way the views were created, just wondering what those are.
This actually works very well in my testing. Essentially the Context passed to the layout inflater or view constructor will be the context of the view throughout its lifetime (makes sense). The only time these will mismatch is if you use different contexts (such as the application context) to inflate some parts of your layout... the context for views inflated via the activity's setContentView() will have the Activity set as theirs.

context vs views

can anyone explain the difference between context and views and when do we go for context or view ? In most of the program I find either context or view being passed to certain methods , what is actual need of passing context or view to methods?
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.
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().

Categories

Resources