在Android N上使用更改的显示缩放获取屏幕大小(以px为单位)

4
我在Android N上更改了显示缩放比例,但计算显示尺寸时遇到了问题。
在Android N上,您可以更改显示缩放比例(请参见此处),但如果用户从Android设置中设置缩放比例,则显示大小(...getSize())不会改变...
有什么解决办法吗?我需要使用以px为单位乘以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.

如果我设置一个较小的缩放比例,我就会遇到这个问题:
默认:
enter image description here



缩小后:
窗口组件变得太小了:
enter image description here

宽度以像素为单位不变,只有密度发生了变化:

缩小

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}

可能有一个解决方案吗? int smartphoneComponentWidth = ((smartphoneDisplayWidth*scaledDensity) / serverDisplayWidth) * serverComponentWidth; - Giovesoft
1
Android N 的缩放功能超出了应用程序的范围。此外,如果您在应用程序中只包含 Android N 中已有的功能,那么您将大大限制可能的客户数量。 - from56
1个回答

1
你应该使用dp值来创建视图,而不是px。当像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。这是更方便和快速的解决方案。

是的,将宽度乘以缩放密度?请看我的评论。 我不能使用MATCH和WRAP,因为该应用程序完全动态配置在Web服务器上,并且必须在iOS和Android上运行 :-) - Giovesoft
将宽度和采样密度相乘不起作用。我认为您需要将宽度和密度差乘以默认密度和其他密度(小、大或其他)......还有其他建议吗? - Giovesoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接