如何在安卓系统中编程获取屏幕尺寸

85

Android将屏幕大小定义为Normal、Large、XLarge等。它会自动选择合适文件夹中的静态资源。我需要在我的Java代码中使用当前设备的此数据。DisplayMetrics只提供有关当前设备密度的信息,没有关于屏幕尺寸的信息可用。

我在grep代码中找到了ScreenSize枚举类型,这里。但是,在4.0 SDK中似乎无法使用。是否有一种方法可以获取这些信息?

13个回答

125

将此代码复制并粘贴到您的Activity中,当执行它时,它将Toast设备的屏幕大小类别。

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();

18
我使用了这个代码,并在不同的模拟器上运行,包括大屏幕、中等屏幕和小屏幕。但我得到了一个正常大小的 Toast 提示框,你有什么方法可以解决这个问题吗? - Palaniraja

72
private static String getScreenResolution(Context context)
{
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    return "{" + width + "," + height + "}";
}

3
你的代码输出结果不包括底部的软触摸按钮以及顶部的状态栏和工具栏 @David - Umar Ata
正是我想要的!运行得非常好。 - Itoun
谢谢。这段代码在安卓模拟器的手机和平板上运行良好。但是当我旋转平板时,分辨率数值没有翻转,而是实际值发生了变化。但对于手机来说,它可以正常工作。我该如何解决这个问题? - SAIFI369
它帮助了我很多。当您在Android中使用动画时,它确实非常有用,而且不需要使用Layout weight和Layout percentage。 - Abdullah Sheikh

4
DisplayMetrics displayMetrics = new DisplayMetrics();

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

int width = displayMetrics.widthPixels;

int height = displayMetrics.heightPixels;

谢谢。这段代码在安卓模拟器的手机和平板上运行良好。但是当我旋转平板时,分辨率数值没有翻转,而是实际值发生了变化。但对于手机来说,它可以正常工作。我该如何解决这个问题? - SAIFI369

4

我认为这是一段非常简单明了的代码!

public Map<String, Integer> deriveMetrics(Activity activity) {
    try {
        DisplayMetrics metrics = new DisplayMetrics();

        if (activity != null) {
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        }

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("screenWidth", Integer.valueOf(metrics.widthPixels));
        map.put("screenHeight", Integer.valueOf(metrics.heightPixels));
        map.put("screenDensity", Integer.valueOf(metrics.densityDpi));

        return map;
    } catch (Exception err) {
        ; // just use zero values
        return null;
    }
}

现在这种方法可以独立地在任何地方使用。无论您想获取有关设备屏幕的信息的位置是哪里,都可以按如下方式执行:

        Map<String, Integer> map = deriveMetrics2(this);
        map.get("screenWidth");
        map.get("screenHeight");
        map.get("screenDensity");

希望这对某些人有所帮助,并且可能会发现使用起来更加简单。如果需要重新纠正或改进,请不要犹豫让我知道!:-)
干杯!!!

谢谢。这段代码在安卓模拟器的手机和平板上运行良好。但是当我旋转平板时,分辨率数值没有翻转,而是实际值发生了变化。但对于手机来说,它可以正常工作。我该如何解决这个问题? - SAIFI369

4

获取DisplayMetrics的方法:

1.

val dm = activity.resources.displayMetrics
val dm = DisplayMetrics() 
activity.windowManager.defaultDisplay.getMetrics(dm)
  1. val dm = DisplayMetrics() val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager wm..defaultDisplay.getMetrics(dm)

然后获取

屏幕密度以每英寸点数表示。可以是DENSITY_LOW,DENSITY_MEDIUM或DENSITY_HIGH。

dm.densityDpi

可用显示尺寸的绝对高度,以像素为单位。
dm.heightPixels

可用显示区域的绝对宽度(以像素为单位)。
dm.widthPixels

屏幕在X维度上的每英寸精确物理像素。
dm.xdpi

屏幕在Y轴上每英寸的实际物理像素。
dm.ydpi

显示度量值


3
您可以使用以下代码获取显示器的像素尺寸。
Display display = getWindowManager().getDefaultDisplay();
SizeUtils.SCREEN_WIDTH = display.getWidth();
SizeUtils.SCREEN_HEIGHT = display.getHeight();

3
这不是原帖所询问的内容。 - Alex Lockwood
getHeightgetWidth自API 16:Android 4.1(Jelly Bean)起已被弃用。 - Bruno Bieri

2
代码将以以下格式为您提供结果:宽度 x 高度
String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;

如果OP使用的设备不是1440x2560怎么办?你的回答应该更具体。代码可能很好,但描述并不总是有效的。 - Magiczne

2

带装饰(包括按钮栏):

private static String getScreenResolution(Context context) {
    DisplayMetrics metrics = new DisplayMetrics();
    ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(metrics);
    return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}

没有装饰:

private static String getScreenResolution(Context context) {
    DisplayMetrics metrics = new DisplayMetrics();
    ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
    return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}

这两种方法的区别在于Display类中的getMetrics()方法和getRealMetrics()方法。


1
我需要这个来解决我的几个应用程序问题。以下代码是我解决问题的方法。只是在onCreate中展示了代码。这是一个独立的应用程序,可在任何设备上运行以返回屏幕信息。
setContentView(R.layout.activity_main);
    txSize = (TextView) findViewById(R.id.tvSize);

    density = (TextView) findViewById(R.id.density);
    densityDpi = (TextView) findViewById(R.id.densityDpi);
    widthPixels = (TextView) findViewById(R.id.widthPixels);
    xdpi = (TextView) findViewById(R.id.xdpi);
    ydpi = (TextView) findViewById(R.id.ydpi);

    Configuration config = getResources().getConfiguration();

    if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
        Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
        txSize.setText("Large screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
        Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Normal sized screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
        Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Small sized screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
        Toast.makeText(this, "xLarge sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Small sized screen");
    } else {
        Toast.makeText(this,
                "Screen size is neither large, normal or small",
                Toast.LENGTH_LONG).show();
        txSize.setText("Screen size is neither large, normal or small");
    }

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

    Log.i(TAG, "density :" + metrics.density);
    density.setText("density :" + metrics.density);

    Log.i(TAG, "D density :" + metrics.densityDpi);
    densityDpi.setText("densityDpi :" + metrics.densityDpi);

    Log.i(TAG, "width pix :" + metrics.widthPixels);
    widthPixels.setText("widthPixels :" + metrics.widthPixels);

    Log.i(TAG, "xdpi :" + metrics.xdpi);
    xdpi.setText("xdpi :" + metrics.xdpi);

    Log.i(TAG, "ydpi :" + metrics.ydpi);
    ydpi.setText("ydpi :" + metrics.ydpi);

还有一个简单的XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/tvSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/density"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/densityDpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/widthPixels"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/xdpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/ydpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />


1

西蒙-

不同的屏幕尺寸具有不同的像素密度。您手机上的4英寸显示屏可能比26英寸电视拥有更多或更少的像素。如果我理解正确,他想要检测当前屏幕属于哪个尺寸组,小型、普通、大型或超大型。我能想到的唯一方法是检测像素密度并使用它来确定屏幕的实际尺寸。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接