Reputation: 33996
I'm trying to get screen dimensions inside page adapter. I could get it inside MainActivity
and pass it to the adapter but it would be better to get it there. How can I do it, either directly inside the adapter or inside instantiateItem
?
This is my code:
public class MyPagerAdapter extends PagerAdapter {
Display display = getWindowManager().getDefaultDisplay(); // The method getWindowManager() is undefined for the type MyPagerAdapter
display.getSize(size);
...
}
Upvotes: 3
Views: 13549
Reputation: 1583
you can Do this with WindowManager
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Upvotes: 0
Reputation: 159
public class MyPagerAdapter extends PagerAdapter {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int pxWidth = displayMetrics.widthPixels;
float dpWidth = pxWidth / displayMetrics.density;
int pxHeight = displayMetrics.heightPixels;
float dpHeight = pxHeight / displayMetrics.density;
}
Upvotes: 3
Reputation: 74098
You're almost there. You already have a context
. With that you can retrieve a WindowManager
via getSystemService(WINDOW_SERVICE)
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Upvotes: 15
Reputation: 188
From any context reference (such as in your intantiateItem
), you can get a reference to the DisplayMetrics
class by doing
context.getResources().getDisplayMetrics()
Which gives you a reference to the DisplayMetrics
class DisplayMetrics
Particularly of use to you will be the widthPixels
and heightPixels
attributes of this, which return the raw pixel height and width for the device.
Upvotes: 12