Topwo博客
首页
博客
项目
您现在的位置是:
Topwo博客
>>
Android
文章
Android 获取屏幕宽度和高度的几种方法
发布时间:2023-06-05
作者:Topwo
来源:原创
点击:311
### 方法1 ```java Display defaultDisplay = getWindowManager().getDefaultDisplay(); Point point = new Point(); defaultDisplay.getSize(point); int x = point.x; int y = point.y; Log.i(TAG, "x = " + x + ",y = " + y);//x = 1440,y = 2768 ``` ### 方法2 ```java Rect outSize = new Rect(); getWindowManager().getDefaultDisplay().getRectSize(outSize); int left = outSize.left; int top = outSize.top; int right = outSize.right; int bottom = outSize.bottom; Log.d(TAG, "left = " + left + ",top = " + top + ",right = " + right + ",bottom = " + bottom);//left = 0,top = 0,right = 1440,bottom = 2768 ``` ### 方法3 ```java DisplayMetrics outMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(outMetrics); int widthPixels = outMetrics.widthPixels; int heightPixels = outMetrics.heightPixels; Log.i(TAG, "widthPixels = " + widthPixels + ",heightPixels = " + heightPixels);//widthPixels = 1440, heightPixels = 2768 ``` 方法2和方法3查看源码可知其实是一样的逻辑。 ```java public void getSize(Point outSize) { synchronized (this) { updateDisplayInfoLocked(); mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments()); outSize.x = mTempMetrics.widthPixels; outSize.y = mTempMetrics.heightPixels; } } public void getMetrics(DisplayMetrics outMetrics) { synchronized (this) { updateDisplayInfoLocked(); mDisplayInfo.getAppMetrics(outMetrics, getDisplayAdjustments()); } } ``` ### 方法4 ```java Point outSize = new Point(); getWindowManager().getDefaultDisplay().getRealSize(outSize); int x = outSize.x; int y = outSize.y; Log.w(TAG, "x = " + x + ",y = " + y);//x = 1440,y = 2960 ``` ### 方法5 ```java DisplayMetrics outMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics); int widthPixel = outMetrics.widthPixels; int heightPixel = outMetrics.heightPixels; Log.w(TAG, "widthPixel = " + widthPixel + ",heightPixel = " + heightPixel);//widthPixel = 1440,heightPixel = 2960 ``` 我们注意到方法1,2,3显示屏幕的分辨率是 1440x2768,而方法4,5显示的屏幕的分辨率是1440x2960。为什么是这样了? 答:显示区域以两种不同的方式描述。包括应用程序的显示区域和实际显示区域。 应用程序显示区域指定可能包含应用程序窗口的显示部分,不包括系统装饰。 应用程序显示区域可以小于实际显示区域,因为系统减去诸如状态栏之类的装饰元素所需的空间。 使用以下方法查询应用程序显示区域:getSize(Point),getRectSize(Rect)和getMetrics(DisplayMetrics)。 实际显示区域指定包含系统装饰的内容的显示部分。 即便如此,如果窗口管理器使用(adb shell wm size)模拟较小的显示器,则实际显示区域可能小于显示器的物理尺寸。 使用以下方法查询实际显示区域:getRealSize(Point),getRealMetrics(DisplayMetrics)。 相关资源: android.view WindowManager 应用程序用于与窗口管理器通信的界面。 [https://developer.android.com/reference/android/view/WindowManager#getDefaultDisplay()](https://developer.android.com/reference/android/view/WindowManager#getDefaultDisplay()) Display 提供有关逻辑显示的大小和密度的信息。 [https://developer.android.com/reference/android/view/Display#getRealMetrics(android.util.DisplayMetrics)](https://developer.android.com/reference/android/view/Display#getRealMetrics(android.util.DisplayMetrics))
上一篇:
Android打开wifi热点
下一篇:
Android知识点