Get screen size in px on Android N with resized magnification
I'm having a problem calculating the screen size on Android N with resized magnification.
With Android N, you can change the display scale (check here )
but the screen size (... getSize ()) does not change if the user sets the scale from Android settings ...
Any idea to solve it? Do I need to use the px size multiplied by the scaledDensity to have the actual display size?
My application dynamically creates windows and components by calculating screen sizes in px, components are created on the server. In short, I make a mathematical proportion between the width set on the server and the width of the smartphone screen:
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
display.getRealSize(sizePoint);
}else{
display.getSize(sizePoint);
}
int smartphoneDisplayWidth = sizePoint.x;
int smartphoneDisplayHeight = sizePoint.y;
int serverDisplayWidth = 720px; //this come from the server
int serverComponentWidth = 720px; //this come from the server
int smartphoneComponentWidth = (smartphoneDisplayWidth/serverDisplayWidth)*serverComponentWidth;
//ex: smartphoneComponentWidth = (1080/720)*720 = 1080; the component widht on the smartphone will be 1080px.
If set to smaller scale, I have this problem:
default : small :
windows components should be small:
The width in px does not change, it only changes the density:
small
DisplayMetrics{density=2.2250001, width=1080, height=1813, scaledDensity=2.2250001, xdpi=422.03, ydpi=424.069}
default
DisplayMetrics{density=2.625, width=1080, height=1794, scaledDensity=2.625, xdpi=422.03, ydpi=424.069}
big
DisplayMetrics{density=2.875, width=1080, height=1782, scaledDensity=2.875, xdpi=422.03, ydpi=424.069}
more
DisplayMetrics{density=3.125, width=1080, height=1770, scaledDensity=3.125, xdpi=422.03, ydpi=424.069}
the largest
DisplayMetrics{density=3.375, width=1080, height=1758, scaledDensity=3.375, xdpi=422.03, ydpi=424.069}
source to share
You should create views using dp instead of px. When density changes (for example, in nugat settings), you see the result on the second screen.
Perhaps you create a layout like this:
int screenWidth = <value>;
LayoutParams lp = new LayoutParams(screenWidth, 200);
view.setlayoutparams(lp);
You should use density:
float sampleDensity = 2f; // get from DisplayMetrics
int screenWidth = <value>;
LayoutParams lp = new LayoutParams((int) (screenWidth * sampleDensity), 200);
view.setlayoutparams(lp);
Another reason is that you may not be updating the layouts after changing the configuration. The best solution - the use MATCH_PARENT
and WRAP_CONTENT
in LayoutParams. This is a more convenient and faster solution.
source to share