android - 在android中捕获屏幕大小的正确方法是什么
问题描述
在谷歌上搜索我发现了各种获取屏幕尺寸的方法,这就是我得到的。
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
Log.i(TAG, "first way width = "+size.x);
Log.i(TAG, "first way height = "+size.y);
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
Log.i(TAG, "second way width = "+width);
Log.i(TAG, "second way height = "+height);
int height2 = Resources.getSystem().getDisplayMetrics().heightPixels;
int width2 = Resources.getSystem().getDisplayMetrics().widthPixels;
Log.i(TAG, "third way width = "+width2);
Log.i(TAG, "third way height = "+height2);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height3 = displaymetrics.heightPixels;
int width3 = displaymetrics.widthPixels;
Log.i(TAG, "fourth way width = "+width3);
Log.i(TAG, "fourth way height = "+height3);
在记录所有都给出相同的结果。我想知道所有这些方法或任何特定用例之间是否有任何区别?提前致谢。
解决方案
不要重新发明轮子使用它,这是检查屏幕高度和宽度的代码:
/**
* Return the width of screen, in pixel.
*
* @return the width of screen, in pixel
*/
public static int getScreenWidth() {
WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
if (wm == null) {
return Utils.getApp().getResources().getDisplayMetrics().widthPixels;
}
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wm.getDefaultDisplay().getRealSize(point);
} else {
wm.getDefaultDisplay().getSize(point);
}
return point.x;
}
/**
* Return the height of screen, in pixel.
*
* @return the height of screen, in pixel
*/
public static int getScreenHeight() {
WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
if (wm == null) {
return Utils.getApp().getResources().getDisplayMetrics().heightPixels;
}
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wm.getDefaultDisplay().getRealSize(point);
} else {
wm.getDefaultDisplay().getSize(point);
}
return point.y;
}
BlankJ从这个帮助库中挑选出来的
推荐阅读
- python - 将补丁装饰器移动到函数中
- python - 'return' 超出功能错误 keras 预测值
- python - 使用 Python 扩展 API 包装复杂的 C++ 类
- forms - Xamarin Forms:如何在 ListView 中处理大数据?
- view - 更新由管理的视图的属性“填充”时出错:RNSVGLine
- c# - 如何在 C# 中使用 LINQ 获取列表中的元素并获取下一项?
- django - Django 迁移完整性错误列包含空值
- javascript - 如何将逗号分隔的列值从 sql server 传递到 c# 中的变量中
- machine-learning - 在主成分分析 (PCA) 中使用 4 个成分
- typo3 - 为什么 noTrimWrap 在以下 TypoScript 中不起作用?