您好我想询问有关高效方法调整所有移动设备和平板电脑布局的方法有时我无法使用wrap_content
和layout_weight
我将大小设置为java中的设备大小,如下所示:
ImageView img;
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
img.getLayoutParams().width = width* 7 / 10;
当旋转屏幕时,我使用此方法来更改百分比
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE&& getResources().getBoolean(R.bool.isTablet)) {
width=(int) (width * 0.7);
}
我在问这个程序是否比为每个屏幕尺寸/方向使用多XML文件更有效
答案 0 :(得分:2)
实际上这取决于场景。有时维护xml是有效且容易的,有时需要动态计算。您可以浏览https://developer.android.com/guide/practices/screens_support.html链接。它会给你一些想法。在上面的宽度/高度计算代码中,有时您可能无法获得某些设备的正确结果。下面是在运行时准确支持所有版本的Android设备分辨率(宽度,高度)的代码。
private void calculateDeviceResolution(Activity context) {
Display display = context.getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= 17) {
//new pleasant way to get real metrics
DisplayMetrics realMetrics = new DisplayMetrics();
display.getRealMetrics(realMetrics);
realWidth = realMetrics.widthPixels;
realHeight = realMetrics.heightPixels;
} else if (Build.VERSION.SDK_INT >= 14) {
//reflection for this weird in-between time
try {
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
realWidth = (Integer) mGetRawW.invoke(display);
realHeight = (Integer) mGetRawH.invoke(display);
} catch (Exception e) {
//this may not be 100% accurate, but it's all we've got
realWidth = display.getWidth();
realHeight = display.getHeight();
Constants.errorLog("Display Info", "Couldn't use reflection to get the real display metrics.");
}
} else {
//This should be close, as lower API devices should not have window navigation bars
realWidth = display.getWidth();
realHeight = display.getHeight();
}
}