简体   繁体   English

Android中获取屏幕宽高

[英]Get screen width and height in Android

How can I get the screen width and height and use this value in:如何获取屏幕宽度和高度并将此值用于:

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

Using this code, you can get the runtime display's width & height:使用此代码,您可以获得运行时显示的宽度和高度:

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

In a view you need to do something like this:在视图中,您需要执行以下操作:

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

In some scenarios, where devices have a navigation bar, you have to check at runtime:在某些情况下,设备有导航栏,您必须在运行时检查:

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

If the device has a navigation bar, then count its height:如果设备有导航栏,那么计算它的高度:

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;
}

So the final height of the device is:所以设备的最终高度为:

int height = displayMetrics.heightPixels + getNavigationBarHeight();

There is a very simple answer and without pass context有一个非常简单的答案,没有通过上下文

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

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

Note: if you want the height include navigation bar, use method below注意:如果您希望高度包括导航栏,请使用下面的方法

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;
    }

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:只是为了通过 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(); 
}

Why not为什么不

DisplayMetrics displaymetrics = getResources().getDisplayMetrics(); DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

then use然后使用

displayMetrics.widthPixels (heightPixels) displayMetrics.widthPixels (heightPixels)

It's very easy to get in Android:在Android中很容易获得:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;

Kotlin Version via Extension Property Kotlin Version通过Extension Property

If you want to know the size of the screen in pixels as well as dp , using these extension properties really helps:如果您想知道以像素为单位的屏幕大小以及dp ,使用这些扩展属性确实有帮助:


DimensionUtils.kt 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()


Usage:用法:

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")
    }
}

Result:结果:

When the device is in portrait orientation:当设备处于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

When the device is in landscape orientation:当设备处于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

Try below code :-试试下面的代码:-

1. 1.

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

2. 2.

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

or要么

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

3. 3.

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

metrics.heightPixels;
metrics.widthPixels;
DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;

I suggest you create extension functions.我建议你创建扩展函数。

/**
 * 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()

For kotlin user's对于 kotlin 用户

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

And in Activity you could use it like在 Activity 你可以像这样使用它

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

Or in fragment或者在片段中

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }
DisplayMetrics dimension = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dimension);
        int width = dimension.widthPixels;
        int height = dimension.heightPixels;

Get the value of screen width and height.获取屏幕宽度和高度的值。

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

None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.对于 Chrome OS 多显示器或即将推出的可折叠设备,此处的所有答案均无效。

When looking for the current configuration, always use the configuration from your current activity in getResources().getConfiguration() .在查找当前配置时,请始终使用getResources().getConfiguration()当前活动的配置。 Do not use the configuration from your background activity or the one from the system resource.不要使用来自后台活动的配置或来自系统资源的配置。 The background activity does not have a size, and the system's configuration may contain multiple windows with conflicting sizes and orientations , so no usable data can be extracted.后台活动没有大小,系统配置可能包含多个大小和方向冲突的窗口,因此无法提取可用数据。

So the answer is所以答案是

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

Full way to do it, that returns the true resolution:完整的方法,返回真实的分辨率:

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

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:而且由于这可以在不同的方向上改变,这里有一个解决方案(在 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)
}

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.正如android官方文档所说,默认显示使用 Context#getDisplay() 因为此方法在 API 级别 30 中已弃用。

getWindowManager().获取窗口管理器()。 getDefaultDisplay (). getDefaultDisplay ()。 getMetrics (displayMetrics); getMetrics (displayMetrics);

This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:下面给出的这段代码是在 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
    }
}
Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();
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;
    }
}

I use the following code to get the screen dimensions我使用以下代码来获取屏幕尺寸

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

Methods shown here are deprecated/outdated but this is still working.Require API 13此处显示的方法已弃用/过时,但这仍然有效。需要 API 13

check it out一探究竟

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

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.正如android官方文档所说,默认显示使用 Context#getDisplay() 因为此方法在 API 级别 30 中已弃用。

getWindowManager().获取窗口管理器()。 getDefaultDisplay (). getDefaultDisplay ()。 getMetrics (displayMetrics); getMetrics (displayMetrics);

This bowl of code help to determine width and height.这碗代码有助于确定宽度和高度。

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;
}

For the Height:对于高度:

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;
}

Try this code for Kotlin试试这个Kotlin代码

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

You can get width and height from context您可以从上下文中获取宽度和高度

java:爪哇:

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

kotlin科特林

    val width: Int = context.resources.displayMetrics.widthPixels
    val height: Int = context.resources.displayMetrics.heightPixels
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)

}}

This is an extension function and you can use in your activity in this way:这是一个扩展功能,您可以通过以下方式在您的活动中使用:

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

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

Just use the function below that returns width and height of the screen size as an array of integers只需使用下面的函数将屏幕大小的宽度和高度作为整数数组返回

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;

    }

On your onCreate function or button click add the following code to output the screen sizes as shown below在您的 onCreate 函数或按钮上单击添加以下代码以输出屏幕尺寸,如下所示

 int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

How can I get the screen width and height and use this value in:如何获取屏幕的宽度和高度,并在以下位置使用此值:

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

I found weigan 's answer best one in this page, here is how you can use that in Xamarin.Android :我在此页面中找到了weigan的最佳答案,以下是在Xamarin.Android使用它的Xamarin.Android

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

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

Screen resolution is total no of pixel in screen.屏幕分辨率是屏幕中像素的总数。 Following program will extract the screen resolution of the device.以下程序将提取设备的屏幕分辨率。 It will print screen width and height.它将打印屏幕宽度和高度。 Those values are in pixel.这些值以像素为单位。

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;

} }

How can I get the screen width and height and use this value in:如何获取屏幕的宽度和高度,并在以下位置使用此值:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT - 
        game.findViewById(R.id.flag).getHeight());
}
    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;
    }

I updated answer for Kotlin language!我更新了 Kotlin 语言的答案!

For Kotlin: You should call Window Manager and get metrics.对于 Kotlin:您应该调用 Window Manager 并获取指标。 After that easy way.在那个简单的方法之后。

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

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

How can we use it effectively in independent activity way with Kotlin language?我们如何通过 Kotlin 语言以独立活动的方式有效地使用它?

Here, I created a method in general Kotlin class.在这里,我在一般 Kotlin 类中创建了一个方法。 You can use it in all activities.您可以在所有活动中使用它。

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;

this may be not work in some case.在某些情况下这可能不起作用。 for the getMetrics comments :对于getMetrics 评论

Gets display metrics that describe the size and density of this display.获取描述此显示的大小和密度的显示指标。 The size returned by this method does not necessarily represent the actual raw size (native resolution) of the display.此方法返回的大小不一定代表显示器的实际原始大小(原始分辨率)。

  1. The returned size may be adjusted to exclude certain system decor elements that are always visible.可以调整返回的大小以排除某些始终可见的系统装饰元素。

  2. It may be scaled to provide compatibility with older applications that were originally designed for smaller displays.它可以扩展以提供与最初为较小显示器设计的旧应用程序的兼容性。

  3. It can be different depending on the WindowManager to which the display belongs.根据显示所属的 WindowManager,它可能会有所不同。

  • If requested from non-Activity context (eg Application context via (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)) metrics will report the size of the entire display based on current rotation and with subtracted system decoration areas.如果从非活动上下文(例如通过 (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE))的应用程序上下文请求,度量将报告基于当前旋转和减去系统装饰区域的整个显示的大小。

  • If requested from activity (either using getWindowManager() or (WindowManager) getSystemService(Context.WINDOW_SERVICE)) resulting metrics will correspond to current app window metrics.如果从活动(使用 getWindowManager() 或 (WindowManager) getSystemService(Context.WINDOW_SERVICE))请求,则结果指标将对应于当前应用程序窗口指标。 In this case the size can be smaller than physical size in multi-window mode.在这种情况下,大小可以小于多窗口模式下的物理大小。

So, to get the real size:因此,要获得实际尺寸:

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

or:要么:

Point point = new Point();
getWindowManager().getDefaultDisplay().getRealSize(point);
int height = point.y;
int width = point.x;
@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;
  }

Using that method you can get screen height.使用该方法可以获得屏幕高度。 if you want to get width change displayMetrics.heightPixels to displayMetrics.widthPixels .如果你想获得宽度改变displayMetrics.heightPixelsdisplayMetrics.widthPixels

And it also include required api Build version.它还包括所需的 api Build 版本。

Seems like all these answers fail for my Galaxy M51 with Android 11. After doing some research around I found this code :对于我的带有 Android 11 的 Galaxy M51,似乎所有这些答案都失败了。在做了一些研究之后,我发现了这个代码:

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

shows my true device resolution of 1080x2400, the rest only return 810x1800.显示我的真实设备分辨率为 1080x2400,其余仅返回 810x1800。

As getMetrics and getRealMetrics are deprecated, Google recommends to determine the screen width and height as follows:由于 getMetrics 和 getRealMetrics 已弃用,Google 建议按如下方式确定屏幕宽度和高度:

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

However, I've figured out another methode that gives me the same results:但是,我想出了另一种方法,它给了我相同的结果:

Configuration configuration = mContext.getResources().getConfiguration();
Display.Mode mode = display.getMode();
int widthPixels = mode.getPhysicalWidth();
int heightPixels = mode.getPhysicalHeight();

Some methods, applicable for retrieving screen size, are deprecated in API Level 31 , including Display.getRealMetrics() and Display.getRealSize() .一些适用于检索屏幕尺寸的方法在API 级别 31中已弃用,包括Display.getRealMetrics()Display.getRealSize() Starting from API Level 30 we can use WindowManager#getCurrentWindowMetrics() .API 级别 30开始,我们可以使用WindowManager#getCurrentWindowMetrics() The clean way to get screen size is to create some Compat class, eg:获取屏幕大小的干净方法是创建一些 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())
        }
    }
}

Calling ScreenMetricsCompat.getScreenSize(this).height in Activity we can get a screen size.Activity调用ScreenMetricsCompat.getScreenSize(this).height我们可以得到一个屏幕尺寸。

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

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

After trying lots of versions above, I figured out an answer in Kotlin. It accurately returns the resolutions that are advertised for the devices.在尝试了上面的很多版本之后,我在 Kotlin 中找到了答案。它准确地返回了为设备宣传的分辨率。 Please let me know if this does not work on older devices--I only have relatively new ones at the moment.如果这在旧设备上不起作用,请告诉我——目前我只有相对较新的设备。

This solution uses no deprecated functions (as of Jan 2023).此解决方案不使用已弃用的功能(截至 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
    }
}

How can I get the screen width and height and use this value in:如何获取屏幕的宽度和高度,并在以下位置使用此值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM