我在 Android N 上更改显示缩放后计算显示大小时遇到问题。
使用 Android N,您可以更改显示缩放(检查 here)
但是如果用户从 Android 设置中设置缩放,显示大小 (...getSize()) 不会改变...
有解决办法吗?我是否必须使用以像素为单位的大小乘以 scaledDensity 以获得真实的显示大小?
我的应用动态创建窗口和组件,以像素为单位计算屏幕尺寸,这些组件是在服务器上设计的。
简而言之,我根据服务器上设置的宽度和智能手机屏幕的宽度进行数学比例计算:
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.
如果我设置较小的缩放比例,我会遇到这个问题:
默认:
小:
Windows 组件太小:
以 px 为单位的宽度不会改变,它只会改变密度:
小
DisplayMetrics{density=2.2250001, width=1080, height=1813, scaledDensity=2.2250001, xdpi=422.03, ydpi=424.069}
默认
DisplayMetrics{density=2.625, width=1080, height=1794, scaledDensity=2.625, xdpi=422.03, ydpi=424.069}
大
DisplayMetrics{density=2.875, width=1080, height=1782, scaledDensity=2.875, xdpi=422.03, ydpi=424.069}
更大
DisplayMetrics{density=3.125, width=1080, height=1770, scaledDensity=3.125, xdpi=422.03, ydpi=424.069}
最大
DisplayMetrics{density=3.375, width=1080, height=1758, scaledDensity=3.375, xdpi=422.03, ydpi=424.069}
最佳答案
您应该使用 dp 值而不是 px 创建 View 。当密度发生变化时(如 nugat 设置),您会在第二个屏幕中看到结果。
可能你创建这样的布局:
int screenWidth = <value>;
LayoutParams lp = new LayoutParams(screenWidth, 200);
view.setlayoutparams(lp);
你应该使用密度:
float sampleDensity = 2f; // get from DisplayMetrics
int screenWidth = <value>;
LayoutParams lp = new LayoutParams((int) (screenWidth * sampleDensity), 200);
view.setlayoutparams(lp);
其他原因可能是您在配置更改后没有更新布局。更好的解决方案是在 LayoutParams 中使用 MATCH_PARENT
和 WRAP_CONTENT
。更方便快捷的解决方案。
关于android - 在更改显示缩放的 Android N 上以 px 为单位获取屏幕大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44519360/