7

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?

Space Ghost
  • 765
  • 2
  • 13
  • 26
  • 2
    http://stackoverflow.com/questions/22966601/what-is-different-between-mainactivity-this-vs-getapplicationcontext/22967165#22967165 – Zohra Khan Apr 11 '14 at 10:23
  • 1
    You can use Activity instance itself in Activity to find screen size, no need of getBaseContext() and in `View`, `getContext()` returns an instance of `Context` that you passed as parameter to view during its initialization i.e. at `new View(Context)`... – Gopal Gopi Apr 11 '14 at 10:23

3 Answers3

5

View.getContext(): Returns the context the view is currently running in.

getBaseContext(): is the activity context itself. Even you can use this

Zohra Khan
  • 5,182
  • 4
  • 25
  • 34
4

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

Nirbhay Mishra
  • 1,629
  • 3
  • 19
  • 35
2

View.getContext() usually returns the context the view of current Activity. ContextWrapper.getBaseContext() is used while accessing a Context from within another context example Activity.

See at - Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Community
  • 1
  • 1
Aduait Pokhriyal
  • 1,529
  • 14
  • 30