我尝试制作一个简单的应用程序,看看我是否可以制作一个固定尺寸的元素,在这种情况下是4厘米宽,无论设备如何。为此,我尝试使用屏幕xDPI,将其用作英寸,乘以常数得到4厘米。在几个不同的设备上尝试后,它似乎不起作用。
final WindowManager w = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
final Display d = w.getDefaultDisplay();
final DisplayMetrics m = new DisplayMetrics();
d.getMetrics(m);
//find the correct x density and multiply it by 1.5748 to get 4cm
float density = m.xdpi;
density = (float) (density * 1.5748);
int intDensity = (int)Math.ceil(density);
//now set the view to be the dimensions that you want, it must be inside of it's own layout?
box.setLayoutParams(new LinearLayout.LayoutParams(intDensity,100));
有什么建议吗?