在Android中获取屏幕宽度和高度

我如何获得屏幕的宽度和高度,并使用这个值在:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, "onMeasure" + widthSpecId);
setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
game.findViewById(R.id.flag).getHeight());
}
722682 次浏览

使用这段代码,你可以得到运行时显示的宽度&高度:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

在视图中,你需要这样做:

((Activity) getContext()).getWindowManager()
.getDefaultDisplay()
.getMetrics(displayMetrics);

在某些情况下,设备有一个导航栏,你必须在运行时检查:

public boolean showNavigationBar(Resources resources)
{
int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
return id > 0 && resources.getBoolean(id);
}

如果设备有一个导航栏,那么计算它的高度:

private int getNavigationBarHeight() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
return 0;
}

所以设备的最终高度是:

int height = displayMetrics.heightPixels + getNavigationBarHeight();

只是通过parag和SpK更新答案,使其与当前SDK的向后兼容性保持一致:

int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();


if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}

试试下面的代码:-

1.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

2.

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();

3.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);


metrics.heightPixels;
metrics.widthPixels;
DisplayMetrics dimension = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dimension);
int width = dimension.widthPixels;
int height = dimension.heightPixels;

为什么不

DisplayMetrics DisplayMetrics = getResources().getDisplayMetrics();

然后使用

displayMetrics。widthPixels (heightPixels)

这里显示的方法已弃用/过时,但仍然可以工作。需要API 13

看看吧

Display disp= getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
disp.getSize(size);
int width = size.x;
int height = size.y;

获取屏幕宽度和高度的值。

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;

有一个非常简单的答案,没有通过上下文

public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}


public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}

注:如果你想要高度包括导航条,使用下面的方法

WindowManager windowManager =
(WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
final Display display = windowManager.getDefaultDisplay();
Point outPoint = new Point();
if (Build.VERSION.SDK_INT >= 19) {
// include navigation bar
display.getRealSize(outPoint);
} else {
// exclude navigation bar
display.getSize(outPoint);
}
if (outPoint.y > outPoint.x) {
mRealSizeHeight = outPoint.y;
mRealSizeWidth = outPoint.x;
} else {
mRealSizeHeight = outPoint.x;
mRealSizeWidth = outPoint.y;
}
DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;
Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();

只需使用下面的函数,它以整数数组的形式返回屏幕大小的宽度和高度

private int[] getScreenSIze(){
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
int w = displaymetrics.widthPixels;


int[] size={w,h};
return size;


}

在onCreate函数或按钮上单击添加以下代码以输出屏幕大小,如下所示

 int[] screenSize= getScreenSIze();
int width=screenSize[0];
int height=screenSize[1];
screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);
public class DisplayInfo {
int screen_height=0, screen_width=0;
WindowManager wm;
DisplayMetrics displaymetrics;


DisplayInfo(Context context) {
getdisplayheightWidth(context);
}


void getdisplayheightWidth(Context context) {
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
displaymetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displaymetrics);
screen_height = displaymetrics.heightPixels;
screen_width = displaymetrics.widthPixels;
}


public int getScreen_height() {
return screen_height;
}


public int getScreen_width() {
return screen_width;
}
}
       @Override
protected void onPostExecute(Drawable result) {
Log.d("width",""+result.getIntrinsicWidth());
urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 600);


// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;


// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();


// For ICS
URLImageParser.this.container.setHeight((400+URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));


// Pre ICS`enter code here`
URLImageParser.this.container.setEllipsize(null);
}

完整的方法是,返回真实的分辨率:

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
wm.getDefaultDisplay().getRealSize(size);
final int width = size.x, height = size.y;

因为这可以在不同的方向上改变,这里有一个解决方案(在Kotlin中),无论朝向如何,都能得到正确的结果:

/**
* returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
* The result should be consistent no matter the orientation of the device
*/
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
//based on : http://stackoverflow.com/a/9888357/878126
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val config = context.resources.configuration
val rotation = windowManager.defaultDisplay.rotation
return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
Configuration.ORIENTATION_LANDSCAPE
else
Configuration.ORIENTATION_PORTRAIT
}


/**
* returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
*/
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
val screenNaturalOrientation = getScreenNaturalOrientation(context)
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val point = Point()
wm.defaultDisplay.getRealSize(point)
val currentOrientation = context.resources.configuration.orientation
if (currentOrientation == screenNaturalOrientation)
return point
else return Point(point.y, point.x)
}

我发现weigan的答案最好的一个在这个页面,这里是你可以在Xamarin.Android使用它:

public int GetScreenWidth()
{
return Resources.System.DisplayMetrics.WidthPixels;
}


public int GetScreenHeight()
{
return Resources.System.DisplayMetrics.HeightPixels;
}

屏幕分辨率是屏幕中像素的总和。下面的程序将提取设备的屏幕分辨率。它将打印屏幕的宽度和高度。这些值以像素为单位。

public static Point getScreenResolution(Context context) {
// get window managers
WindowManager manager =  (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);


// get width and height
int width = point.x;
int height = point.y;


return point;

试一下芬兰湾的科特林的代码

 val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
var DEVICE_WIDTH = size.x
var DEVICE_HEIGHT = size.y

这里没有一个答案适用于Chrome OS的多显示器,或即将到来的可折叠设备。

在查找当前配置时,始终使用getResources().getConfiguration()中当前活动的配置。不要使用来自后台活动或系统资源的配置。后台活动没有大小,系统配置可能包含多个大小和方向冲突的Windows,所以没有可用的数据可以提取。

所以答案是

val config = context.getResources().getConfiguration()
val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp

对于kotlin用户

fun Activity.displayMetrics(): DisplayMetrics {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics
}

在Activity中,你可以使用它

     resources.displayMetrics.let { displayMetrics ->
val height = displayMetrics.heightPixels
val width = displayMetrics.widthPixels
}

或者碎片化

    activity?.displayMetrics()?.run {
val height = heightPixels
val width = widthPixels
}

在Android中很容易获得:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
    int getScreenSize() {
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
//        String toastMsg = "Screen size is neither large, normal or small";
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getRotation();


int i = 0;
switch (screenSize) {


case Configuration.SCREENLAYOUT_SIZE_NORMAL:
i = 1;
//                toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
i = 1;
//                toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
//                toastMsg = "Large screen";
if (orientation == Surface.ROTATION_90
|| orientation == Surface.ROTATION_270) {
// TODO: add logic for landscape mode here
i = 2;
} else {
i = 1;
}




break;
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
if (orientation == Surface.ROTATION_90
|| orientation == Surface.ROTATION_270) {
// TODO: add logic for landscape mode here
i = 4;
} else {
i = 3;
}


break;




}
//        customeToast(toastMsg);
return i;
}

我使用下面的代码来获取屏幕尺寸

getWindow().getDecorView().getWidth()
getWindow().getDecorView().getHeight()

我更新了Kotlin语言的答案!

对于Kotlin:您应该调用窗口管理器并获取指标。在那简单的方法之后。

val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)


var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels

如何用Kotlin语言有效地独立活动地使用它?

这里,我在一般的Kotlin类中创建了一个方法。你可以在所有活动中使用它。

private val T_GET_SCREEN_WIDTH:String = "screen_width"
private val T_GET_SCREEN_HEIGHT:String = "screen_height"


private fun getDeviceSizes(activity:Activity, whichSize:String):Int{


val displayMetrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(displayMetrics)


return when (whichSize){
T_GET_SCREEN_WIDTH -> displayMetrics.widthPixels
T_GET_SCREEN_HEIGHT -> displayMetrics.heightPixels
else -> 0 // Error
}
}
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

在某些情况下,这可能行不通。对于getMetrics评论:

获取描述此对象的大小和密度的显示指标 显示。此方法返回的大小不一定 表示显示的实际原始大小(原生分辨率)

  1. 返回的大小可以被调整,以排除总是可见的某些系统装饰元素。

  2. 可以进行缩放,以提供与最初为较小显示器设计的旧应用程序的兼容性。

  3. 根据显示所属的WindowManager可以不同。

  • 如果从非活动上下文请求(例如通过(WindowManager)的应用程序上下文) getApplicationContext () .getSystemService (Context.WINDOW_SERVICE)) Metrics将基于当前报告整个显示的大小 旋转和减去系统装饰面积。

  • 如果从activity请求(使用getWindowManager()或(WindowManager) getSystemService(Context.WINDOW_SERVICE))结果 指标将与当前应用程序窗口指标相对应。在这种情况下,在多窗口模式下,大小可以小于物理大小

所以,要得到真正的大小:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

或者:

Point point = new Point();
getWindowManager().getDefaultDisplay().getRealSize(point);
int height = point.y;
int width = point.x;

Kotlin VersionExtension Property

如果你想知道屏幕的像素大小以及dp,使用这些扩展属性真的很有帮助:


DimensionUtils.kt

import android.content.Context
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.RectF
import android.os.Build
import android.util.DisplayMetrics
import android.view.WindowManager
import kotlin.math.roundToInt


/**
* @author aminography
*/


private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }


/**
* Returns boundary of the screen in pixels (px).
*/
val screenRectPx: Rect
get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }


/**
* Returns boundary of the screen in density independent pixels (dp).
*/
val screenRectDp: RectF
get() = screenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }


/**
* Returns boundary of the physical screen including system decor elements (if any) like navigation
* bar in pixels (px).
*/
val Context.physicalScreenRectPx: Rect
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
(applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.run { DisplayMetrics().also { defaultDisplay.getRealMetrics(it) } }
.run { Rect(0, 0, widthPixels, heightPixels) }
} else screenRectPx


/**
* Returns boundary of the physical screen including system decor elements (if any) like navigation
* bar in density independent pixels (dp).
*/
val Context.physicalScreenRectDp: RectF
get() = physicalScreenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }


/**
* Converts any given number from pixels (px) into density independent pixels (dp).
*/
val Number.px2dp: Float
get() = this.toFloat() / displayMetrics.density


/**
* Converts any given number from density independent pixels (dp) into pixels (px).
*/
val Number.dp2px: Int
get() = (this.toFloat() * displayMetrics.density).roundToInt()



用法:

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)


val widthPx = screenRectPx.width()
val heightPx = screenRectPx.height()
println("[PX] screen width: $widthPx , height: $heightPx")


val widthDp = screenRectDp.width()
val heightDp = screenRectDp.height()
println("[DP] screen width: $widthDp , height: $heightDp")


println()
        

val physicalWidthPx = physicalScreenRectPx.width()
val physicalHeightPx = physicalScreenRectPx.height()
println("[PX] physical screen width: $physicalWidthPx , height: $physicalHeightPx")


val physicalWidthDp = physicalScreenRectDp.width()
val physicalHeightDp = physicalScreenRectDp.height()
println("[DP] physical screen width: $physicalWidthDp , height: $physicalHeightDp")
}
}

结果:

当设备在portrait方向时:

[PX] screen width: 1440 , height: 2392
[DP] screen width: 360.0 , height: 598.0


[PX] physical screen width: 1440 , height: 2560
[DP] physical screen width: 360.0 , height: 640.0

当设备在landscape方向时:

[PX] screen width: 2392 , height: 1440
[DP] screen width: 598.0 , height: 360.0


[PX] physical screen width: 2560 , height: 1440
[DP] physical screen width: 640.0 , height: 360.0

正如android官方文档所说,默认显示使用Context#getDisplay(),因为该方法在API级别30中已弃用。

getWindowManager()。# EYZ0()。# EYZ1 (displayMetrics);

这一碗代码有助于确定宽度和高度。

public static int getWidth(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
Display display = context.getDisplay();
if (display != null) {
display.getRealMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
return -1;
}

关于高度:

public static int getHeight(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
Display display = context.getDisplay();
if (display != null) {
display.getRealMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
return -1;
}

正如android官方文档所说,默认显示使用Context#getDisplay(),因为该方法在API级别30中已弃用。

getWindowManager()。# EYZ0()。# EYZ1 (displayMetrics);

下面给出的代码是kotlin,是根据Android的最新版本编写的,帮助您确定宽度和高度:

fun getWidth(context: Context): Int {
var width:Int = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val displayMetrics = DisplayMetrics()
val display: Display? = context.getDisplay()
display!!.getRealMetrics(displayMetrics)
return displayMetrics.widthPixels
}else{
val displayMetrics = DisplayMetrics()
this.windowManager.defaultDisplay.getMetrics(displayMetrics)
width = displayMetrics.widthPixels
return width
}
}


fun getHeight(context: Context): Int {
var height: Int = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val displayMetrics = DisplayMetrics()
val display = context.display
display!!.getRealMetrics(displayMetrics)
return displayMetrics.heightPixels
}else {
val displayMetrics = DisplayMetrics()
this.windowManager.defaultDisplay.getMetrics(displayMetrics)
height = displayMetrics.heightPixels
return height
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static double getHeight() {
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getRealMetrics(displayMetrics);


//int height = displayMetrics.heightPixels;
//int width = displayMetrics.widthPixels;
return displayMetrics.heightPixels;
}

使用该方法可以获得屏幕高度。 如果你想获得宽度更改displayMetrics.heightPixelsdisplayMetrics.widthPixels.

它还包括所需的api构建版本。

你可以从上下文中获取宽度和高度

java:

  int width= context.getResources().getDisplayMetrics().widthPixels;
int height= context.getResources().getDisplayMetrics().heightPixels;

芬兰湾的科特林

    val width: Int = context.resources.displayMetrics.widthPixels
val height: Int = context.resources.displayMetrics.heightPixels

似乎所有这些答案都不适合我的Galaxy M51和Android 11。在做了一些研究之后,我发现了这个代码:

WindowMetrics windowmetrics = MainActivity.getWindowManager().getCurrentWindowMetrics();
Rect rect = windowmetrics.getBounds();
int width = rect.right;
int height =rect.bottom;

显示我的真实设备分辨率为1080x2400,其余只返回810x1800。

由于getMetrics和getRealMetrics已弃用,谷歌建议按如下方式确定屏幕宽度和高度:

WindowMetrics windowMetrics = getActivity().getWindowManager().getMaximumWindowMetrics();
Rect bounds = windowMetrics.getBounds();
int widthPixels = bounds.width();
int heightPixels = bounds.height();

然而,我想出了另一种方法,给我同样的结果:

Configuration configuration = mContext.getResources().getConfiguration();
Display.Mode mode = display.getMode();
int widthPixels = mode.getPhysicalWidth();
int heightPixels = mode.getPhysicalHeight();
fun Activity.getRealScreenSize(): Pair<Int, Int> { //<width, height>
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val size = Point()
display?.getRealSize(size)
Pair(size.x, size.y)
} else {
val size = Point()
windowManager.defaultDisplay.getRealSize(size)
Pair(size.x, size.y)


}}

这是一个扩展函数,你可以这样在你的活动中使用:

 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)


val pair = getRealScreenSize()
pair.first //to get width
pair.second //to get height
}

一些适用于检索屏幕大小的方法在空气污染指数等级31中已弃用,包括Display.getRealMetrics()Display.getRealSize()。从空气污染指数30开始,我们可以使用WindowManager#getCurrentWindowMetrics()。获取屏幕大小的简单方法是创建一些Compat类,例如:

object ScreenMetricsCompat {
private val api: Api =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30()
else Api()


/**
* Returns screen size in pixels.
*/
fun getScreenSize(context: Context): Size = api.getScreenSize(context)


@Suppress("DEPRECATION")
private open class Api {
open fun getScreenSize(context: Context): Size {
val display = context.getSystemService(WindowManager::class.java).defaultDisplay
val metrics = if (display != null) {
DisplayMetrics().also { display.getRealMetrics(it) }
} else {
Resources.getSystem().displayMetrics
}
return Size(metrics.widthPixels, metrics.heightPixels)
}
}


@RequiresApi(Build.VERSION_CODES.R)
private class ApiLevel30 : Api() {
override fun getScreenSize(context: Context): Size {
val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics
return Size(metrics.bounds.width(), metrics.bounds.height())
}
}
}

Activity中调用ScreenMetricsCompat.getScreenSize(this).height,我们可以得到屏幕高度。

我建议您创建扩展函数。

/**
* Return the width and height of the screen
*/
val Context.screenWidth: Int
get() = resources.displayMetrics.widthPixels


val Context.screenHeight: Int
get() = resources.displayMetrics.heightPixels


/**
* Pixel and Dp Conversion
*/
val Float.toPx get() = this * Resources.getSystem().displayMetrics.density
val Float.toDp get() = this / Resources.getSystem().displayMetrics.density


val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)


var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels