lisovaccaro lisovaccaro - 1 month ago 7
Android Question

Get screen dimensions inside page adapter?

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);
...
}

Answer

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.

Comments