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?
It may not answer your question, but it could be useful to know (I was looking for it myself when I came to this question) that if you need a View's dimension but your code is being executed when its layout has not been laid out yet (for example in
onCreate()
) you can setup aViewTreeObserver.OnGlobalLayoutListener
withView.getViewTreeObserver().addOnGlobalLayoutListener()
and put the relevant code that needs the view's dimension there. The listener's callback will be called when the layout will have been laid out.(2012 answer, may be out of date) If you want to support pre Honeycomb, you will need to put in backward compatibility prior to API 13. Something like:
Of course the deprecated methods will eventually be taken out of the the most recent SDKs, but while we still rely on most of our users having Android 2.1, 2.2 and 2.3, this is what we are left with.
This is the code I use for the task:
Seems clean enough and yet, takes care of the deprecation.
Isn't this a much better solution? DisplayMetrics comes with everything you need and works from API 1.
You can also get the actual display (including screen decors, such as Status Bar or software navigation bar) using getRealMetrics, but this works on 17+ only.
Am I missing something?
For getting the screen dimensions use display metrices
Get the height and width in pixels
If you don't want the overhead of WindowManagers, Points, or Displays, you can grab the height and width attributes of the topmost View item in your XML, provided its height and width are set to match_parent. (This is true so long as your layout takes up the entire screen.)
For example, if your XML starts with something like this:
Then
findViewById(R.id.entireLayout).getWidth()
will return the screen's width andfindViewById(R.id.entireLayout).getHeight()
will return the screen's height.