I noticed that inside my class that extends View
, to get the screen size I have to use getContext
DisplayMetrics dispM = getContext.getResources().getDisplayMetrics();
int width = dispM.WidthPixels;
int height = dispM.HeightPixels;
if I wanted to do the same inside my Activity, I have to replace getContext
with getBaseContext
. Why is this the case?
getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity. Save this answer.
getBaseContext() is the method of ContextWrapper . And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)..
You may wonder now, what is the difference between getContext() and getApplicationContext(). The difference is that Application's Context is not UI related. It means that, we shouldn't use it to Inflate a Layout, Start an Activity nor Show a Dialog.
getContext(): It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.
View.getContext(): Returns the context the view is currently running in.
getBaseContext(): is the activity context itself. Even you can use this
getContext() Returns the context the view is currently running in. . Activity.
getBaseContext() : If you need access to a Context from within another context, you use this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With