I created some custom elements, and I want to programmatically place them to the upper right corner (n
pixels from the top edge and m
pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:
int px = screenWidth - m;
int py = screenHeight - n;
How do I get screenWidth
and screenHeight
in the main Activity?
If you want the display dimensions in pixels you can use
getSize
:If you're not in an
Activity
you can get the defaultDisplay
viaWINDOW_SERVICE
:If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).
Before
getSize
was introduced (in API level 13), you could use thegetWidth
andgetHeight
methods that are now deprecated:For the use case you're describing however, a margin/padding in the layout seems more appropriate.
Another way is: DisplayMetrics
We can use
widthPixels
to get information for:Example:
There are times when you need to know the precise dimensions of the available space for a layout when in an activity's onCreate. After some thought I worked out this way of doing it.
If for some reason you don't want to add another activity to the Android manifest, you can do it this way:
I found this did the trick.
I have a splash screen activity with a LinearLayout as a root view that has match_parent for its width & height. This is the code in the
onCreate()
method of that activity. I use these measures in all other activities of the app.Here are the implementations for the methods you see get called above:
This results in the height and width of the usable display, excluding any type of bars (status bar, navigation bar), for all API versions and different types of devices (phones and tablets).
I have tried all possible "solutions" unsuccessfully and I noticed that Elliott Hughes' "Dalvik Explorer" app always shows correct dimension on any Android device/OS version. I ended up looking at his open source project that can be found here: https://code.google.com/p/enh/
Here's all the relevant code:
EDIT: slightly improved version (avoid firing exceptions on non-supported OS version):
First load the XML file and then write this code:
Show width and height according your screen resolution.