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

reb*_*_UA 437 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());
}
Run Code Online (Sandbox Code Playgroud)

Par*_*han 918

使用此代码可以获得运行时 __CODE__

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
Run Code Online (Sandbox Code Playgroud)

在视图中,您需要执行以下操作:

((Activity) getContext()).getWindowManager()
                         .getDefaultDisplay()
                         .getMetrics(displayMetrics);
Run Code Online (Sandbox Code Playgroud)

  • 如果旋转设备,是否交换了宽度和高度? (30认同)
  • @Madeyedexter是的. (14认同)
  • getDefaultDisplay() 和 getMetrics 已弃用 (8认同)
  • 或者只是简单地使用 - getResources().getDisplayMetrics().heightPixels / getResources().getDisplayMetrics().widthPixels (3认同)

wei*_*gan 256

有一个非常简单的答案,没有传递上下文

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

public static int getScreenHeight() {
    return Resources.getSystem().getDisplayMetrics().heightPixels;
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您想要高度包含导航栏,请使用以下方法

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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 这在我的情况下效果更好.不需要上下文. (10认同)
  • 如何获得总屏幕高度?此版本的getScreenHeight排除了所有条形图. (3认同)

dig*_*phd 45

只是为了更新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(); 
}
Run Code Online (Sandbox Code Playgroud)

  • @digiphd不会让Parang的代码适用于所有API版本吗?所有方法都是在API级别8之前引入的,我没有发现它们在android dev网站上被弃用了. (7认同)

Ras*_*iri 27

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

爪哇:

  int width= context.getResources().getDisplayMetrics().widthPixels;
  int height= context.getResources().getDisplayMetrics().heightPixels;
Run Code Online (Sandbox Code Playgroud)

科特林

    val width: Int = context.resources.displayMetrics.widthPixels
    val height: Int = context.resources.displayMetrics.heightPixels
Run Code Online (Sandbox Code Playgroud)


wan*_*934 23

为什么不

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

然后用

displayMetrics.widthPixels(heightPixels)

  • 因为它不会为您提供大多数设备上的真实屏幕尺寸。 (2认同)

ami*_*phy 17

Kotlin Version通过Extension 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()

Run Code Online (Sandbox Code Playgroud)

用法:

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")
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

当设备处于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
Run Code Online (Sandbox Code Playgroud)

当设备处于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
Run Code Online (Sandbox Code Playgroud)


Ser*_*gey 15

一些适用于检索屏幕尺寸的方法在API 级别 31中已弃用,包括Display.getRealMetrics()Display.getRealSize()从API 级别 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())
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*tti 12

我建议你创建扩展函数。

/**
 * 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()
Run Code Online (Sandbox Code Playgroud)


dug*_*ggu 11

尝试以下代码: -

1.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Run Code Online (Sandbox Code Playgroud)

2.

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated
Run Code Online (Sandbox Code Playgroud)

要么

int width = getWindowManager().getDefaultDisplay().getWidth(); 
int height = getWindowManager().getDefaultDisplay().getHeight();
Run Code Online (Sandbox Code Playgroud)

3.

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

metrics.heightPixels;
metrics.widthPixels;
Run Code Online (Sandbox Code Playgroud)

  • 你不觉得2 = 4 (3认同)

小智 10

DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 10

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

WindowMetrics windowMetrics = getActivity().getWindowManager().getMaximumWindowMetrics();
Rect bounds = windowMetrics.getBounds();
int widthPixels = bounds.width();
int heightPixels = bounds.height();
Run Code Online (Sandbox Code Playgroud)

然而,我找到了另一种方法,它给了我相同的结果:

Display display = requireActivity().getDisplay()
Display.Mode mode = display.getMode();
int widthPixels = mode.getPhysicalWidth();
int heightPixels = mode.getPhysicalHeight();
Run Code Online (Sandbox Code Playgroud)

  • 你从哪里得到“display.getMode()”? (2认同)

小智 9

在Android中很容易获得:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
Run Code Online (Sandbox Code Playgroud)

  • 这在模拟器上返回 0 (2认同)

Ali*_*adi 8

对于 kotlin 用户

fun Activity.displayMetrics(): DisplayMetrics {
   val displayMetrics = DisplayMetrics()
   windowManager.defaultDisplay.getMetrics(displayMetrics)
   return displayMetrics
}
Run Code Online (Sandbox Code Playgroud)

在 Activity 你可以像这样使用它

     resources.displayMetrics.let { displayMetrics ->
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
    }
Run Code Online (Sandbox Code Playgroud)

或者在片段中

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }
Run Code Online (Sandbox Code Playgroud)


Ani*_*nia 6

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

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
Run Code Online (Sandbox Code Playgroud)


Epi*_*rce 6

对于 Chrome OS 多显示器或即将推出的可折叠设备,此处的所有答案均无效。

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

所以答案是

val config = context.getResources().getConfiguration()
val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp
Run Code Online (Sandbox Code Playgroud)


Dev*_*vWM 6

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)

}}
Run Code Online (Sandbox Code Playgroud)

这是一个扩展函数,您可以通过以下方式在您的活动中使用:

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

    val pair = getRealScreenSize()
    pair.first //to get width
    pair.second //to get height
}
Run Code Online (Sandbox Code Playgroud)


Cri*_*vez 5

DisplayMetrics dimension = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dimension);
        int width = dimension.widthPixels;
        int height = dimension.heightPixels;
Run Code Online (Sandbox Code Playgroud)


and*_*per 5

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

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

而且由于这可以在不同的方向上改变,这里有一个解决方案(在 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)
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*dav 5

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

获取窗口管理器()。getDefaultDisplay ()。getMetrics (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
    }
}
Run Code Online (Sandbox Code Playgroud)


Sco*_*ggs 5

在尝试了上面的很多版本之后,我在 Kotlin 中找到了答案。它准确地返回为设备宣传的分辨率。如果这不适用于较旧的设备,请告诉我——我目前只有相对较新的设备。

此解决方案不使用已弃用的函数(截至 2023 年 1 月)。

private fun getScreenHeight() : Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val windowMetrics = windowManager.currentWindowMetrics
        val rect = windowMetrics.bounds
        rect.bottom
    } else {
        resources.displayMetrics.heightPixels
    }
}
Run Code Online (Sandbox Code Playgroud)