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?
For API Level 30,
WindowMetrics.getBoundsis to be used. An example of its usage can be found in the linked docs:Old answer:
If you want the display dimensions in pixels you can use
getSize:If you’re not in an
Activityyou can get the defaultDisplayviaWINDOW_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
getSizewas introduced (in API level 13), you could use thegetWidthandgetHeightmethods 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
widthPixelsto get information for:Example: