有没有办法检测设备宽度,以便我们可以根据设备屏幕宽度以编程方式添加视图。例如,单窗格或双窗格。
目前,adpative UI的方式是使用布局XML来实现不同的设备大小。在我们的案例中,这不够灵活。
layout-small/
layout-large/
layout-sw600dp/
我们的首选方法是:layout.xml仅定义根空容器,并根据在运行时检测到的设备大小以编程方式添加视图。
感谢。
答案 0 :(得分:2)
你可以使用这段代码来获取运行时设备的显示宽度和宽度。高度
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
U可以设置为
view.setLayoutParams(new LayoutParams(width, height));
答案 1 :(得分:1)
此代码将在运行时准确支持所有版本的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();
}
}
获得宽度或高度后,您可以像这样设置
view.setLayoutParams(new LayoutParams(realWidth , realHeight ));
答案 2 :(得分:1)
在活动中,
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
int width = dm.widthPixels;
在片段中,
DisplayMetrics dm = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
int width = dm.widthPixels;