如何在Android中以编程方式获取ScreenSize


75

Android将屏幕尺寸定义为Normal Large XLarge等。

它会自动在适当文件夹中的静态资源之间进行选择。我的Java代码中需要有关当前设备的数据。DisplayMetrics仅提供有关当前设备密度的信息。屏幕大小无可用。

我确实在这里的grep代码中找到了ScreenSize枚举, 但是对于4.0 SDK来说,这似乎不可用。有没有办法获取此信息?

Answers:


118

将此代码复制并粘贴到您的代码中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();

14
我在上面使用了它,然后运行不同的仿真器,如大,中,小。但我得到正常的烤面包
屏..

59
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 + "}";
}

1
您的代码给出的结果不包括底部的柔软触摸按钮,顶部的状态栏和工具栏@David
Umar Ata

正是我想要的!像魅力一样工作
伊顿(Itoun)

谢谢。此代码对我在android模拟器手机和平板电脑上正常工作。但是,当我旋转数位板时,分辨率数字不会反转,而是实际值发生了变化。但是对于电话来说,它工作正常。我该如何解决?
SAIFI369

14

确定屏幕尺寸:

int screenSize = getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK;
  switch(screenSize) {
      case Configuration.SCREENLAYOUT_SIZE_LARGE:
        Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
         break;
       case Configuration.SCREENLAYOUT_SIZE_NORMAL:
          Toast.makeText(this, "Normal screen",Toast.LENGTH_LONG).show();
           break;
       case Configuration.SCREENLAYOUT_SIZE_SMALL:
           Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show();
           break;
       default:
           Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();

 }

确定密度:

int density= getResources().getDisplayMetrics().densityDpi;
   switch(density)
  {
  case DisplayMetrics.DENSITY_LOW:
     Toast.makeText(context, "LDPI", Toast.LENGTH_SHORT).show();
      break;
  case DisplayMetrics.DENSITY_MEDIUM:
       Toast.makeText(context, "MDPI", Toast.LENGTH_SHORT).show();
      break;
  case DisplayMetrics.DENSITY_HIGH:
      Toast.makeText(context, "HDPI", Toast.LENGTH_SHORT).show();
      break;
  case DisplayMetrics.DENSITY_XHIGH:
       Toast.makeText(context, "XHDPI", Toast.LENGTH_SHORT).show();
      break;
  }

供参考: http //devl-android.blogspot.in/2013/10/wifi-connectivity-and-hotspot-in-android.html


2
尽管此链接可以回答问题,但最好在此处包括答案的基本部分,并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会无效。
JoseK 2013年

发布的链接不正确。可以在以下位置找到指向相同源的正确链接:devl-android.blogspot.com/2013/10/…。此外,对于使用Kotlin的用户,“&”转换为“ and”。
Panos Gr

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

希望这对外面的人可能有所帮助,并且会发现它更易于使用。如果我需要重新更正或改进,请随时让我知道!:-)

干杯!!!


谢谢。此代码对我在android模拟器手机和平板电脑上正常工作。但是,当我旋转数位板时,分辨率数字不会反转,而是实际值发生了变化。但是对于电话来说,它工作正常。我该如何解决?
SAIFI369

4
DisplayMetrics displayMetrics = new DisplayMetrics();

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

int width = displayMetrics.widthPixels;

int height = displayMetrics.heightPixels;

谢谢。此代码对我在android模拟器手机和平板电脑上正常工作。但是,当我旋转数位板时,分辨率数字不会反转,而是实际值发生了变化。但是对于电话来说,它工作正常。我该如何解决?
SAIFI369

3

您可以使用此代码获得以像素为单位的显示尺寸。

Display display = getWindowManager().getDefaultDisplay();
SizeUtils.SCREEN_WIDTH = display.getWidth();
SizeUtils.SCREEN_HEIGHT = display.getHeight();

3
这不是OP所要的。
Alex Lockwood 2012年

getHeightgetWidth从API 16开始弃用:Android 4.1(Jelly Bean)
Bruno Bieri

3

获取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

显示指标


2

您可以尝试一下,它正在工作

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int ht = displaymetrics.heightPixels;
int wt = displaymetrics.widthPixels;

if ((getResources().getConfiguration().screenLayout &     Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();}

  else if ((getResources().getConfiguration().screenLayout &  Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG)
        .show();

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

 // Determine density
 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 int density = metrics.densityDpi;

 if (density == DisplayMetrics.DENSITY_HIGH) {
Toast.makeText(this,
        "DENSITY_HIGH... Density is " + String.valueOf(density),
        Toast.LENGTH_LONG).show();
 } else if (density == DisplayMetrics.DENSITY_MEDIUM) {
Toast.makeText(this,
        "DENSITY_MEDIUM... Density is " + String.valueOf(density),
        Toast.LENGTH_LONG).show();
 } else if (density == DisplayMetrics.DENSITY_LOW) {
Toast.makeText(this,
        "DENSITY_LOW... Density is " + String.valueOf(density),
        Toast.LENGTH_LONG).show();
 } else {
Toast.makeText(
        this,
        "Density is neither HIGH, MEDIUM OR LOW.  Density is "
                + String.valueOf(density), Toast.LENGTH_LONG)
        .show();
 }

 // These are deprecated
 Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
    .getDefaultDisplay();
 int  width = display.getWidth();
 int height = display.getHeight();

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

西蒙

不同的屏幕尺寸具有不同的像素密度。手机上的4英寸显示屏可能比26英寸电视具有更多或更少的像素。如果林先生正确理解,他想检测当前屏幕是哪个尺寸组,分别是小,普通,大和超大。我唯一能想到的就是检测像素密度,并使用该像素密度来确定屏幕的实际尺寸。


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"
    />


0

如果你是在IE碎片,适配器,型号类或任何其他Java类,做一个非活动不扩展Activity根本getResources()行不通。您可以getActivity()在片段中使用context,也可以将其传递给相应的类。

mContext.getResources()

我建议让一个类说Utils的类将具有用于常规工作的方法。这样做的好处是,您可以在应用程序中调用此方法的任何位置使用单行代码即可获得所需的结果。


0

以下算法可用于识别将在静态资源之间进行选择的类别,并且还可满足较新的XX和XXX高密度

    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    mDensityDpi = displayMetrics.densityDpi;
    mDensity = displayMetrics.density;
    mDisplayWidth = displayMetrics.widthPixels;
    mDisplayHeight = displayMetrics.heightPixels;

    String densityStr = "Unknown";
    int difference, leastDifference = 9999;

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_LOW);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "LOW";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_MEDIUM);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "MEDIUM";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_HIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "HIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XHIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "XHIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXHIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "XXHIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXXHIGH);
    if (difference < leastDifference) {
        densityStr = "XXXHIGH";
    }

    Log.i(TAG, String.format("Display [h,w]: [%s,%s] Density: %s Density DPI: %s [%s]", mDisplayHeight, mDisplayWidth, mDensity, mDensityDpi, densityStr));

0

在Kotlin中获取屏幕分辨率或屏幕尺寸

fun getScreenResolution(context: Context): Pair<Int, Int> {
    try {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val metrics = DisplayMetrics()
        display.getMetrics(metrics)
        val width = metrics.widthPixels
        val height = metrics.heightPixels
        //Log.d(AppData.TAG, "screenSize: $width, $height")
        return Pair(width, height)

    } catch (error: Exception) {
        Log.d(AppData.TAG, "Error : autoCreateTable()", error)
    }

    return Pair(0, 0)
}

0

该代码将以以下格式为您提供结果:宽x高

String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;

如果OP使用的设备未使用1440x2560怎么办?您的答案应该更具体。代码可能不错,但说明并不一定总是有效的。
Magiczne

@Magiczne感谢您的宝贵意见。我编辑了答案
爱丽丝·冰山
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.