如何在android中以编程方式获取屏幕大小

时间:2012-06-28 20:06:34

标签: android android-screen

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

它会自动选择适当文件夹中的静态资源。我需要有关我的java代码中当前设备的数据。 DisplayMetrics仅提供有关当前设备密度的信息。没有关于屏幕尺寸的信息。

我确实在grep代码here中找到了ScreenSize枚举 但是,对于4.0 SDK,我似乎无法使用此功能。有没有办法获取这些信息?

15 个答案:

答案 0 :(得分:111)

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

答案 1 :(得分:47)

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

答案 2 :(得分:12)

确定屏幕尺寸:

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

答案 3 :(得分:3)

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

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

答案 4 :(得分: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();

答案 5 :(得分:2)

我认为这是一段非常直接的简单代码!

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

希望这可能对那里的人有所帮助,并且可能会发现它更容易使用。 如果我需要重新纠正或改进,请不要犹豫,让我知道! : - )

干杯!!!

答案 6 :(得分:2)

DisplayMetrics displayMetrics = new DisplayMetrics();

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

int width = displayMetrics.widthPixels;

int height = displayMetrics.heightPixels;

答案 7 :(得分: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()

答案 8 :(得分:2)

获取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)作为WindowManager wm..defaultDisplay.getMetrics(dm)

然后得到

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

dm.densityDpi

可用显示尺寸的绝对高度(以像素为单位)。

dm.heightPixels

可用显示尺寸的绝对宽度(以像素为单位)。

dm.widthPixels

X维度上每英寸屏幕的确切物理像素。

dm.xdpi

Y尺寸屏幕上每英寸的确切物理像素。

dm.ydpi

DisplayMetrics

答案 9 :(得分:1)

西蒙 -

不同的屏幕尺寸具有不同的像素密度。手机上的4英寸显示屏可能有更多或更少的像素,然后说26英寸电视。如果我正确理解他想要检测当前屏幕中的哪个尺寸组,小,正常,大和超大。我唯一能想到的是检测像素密度并使用它来确定屏幕的实际大小。

答案 10 :(得分: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"
    />

答案 11 :(得分:0)

如果您处于非活动状态,即片段,适配器,模型类或任何其他未扩展Activity的Java类,则getResources()将无效。您可以在片段中使用getActivity()或使用传递给相应类的context

mContext.getResources()

我建议创建一个类,说具有常用工作方法/方法的Utils。这样做的好处是,您可以通过调用此方法的应用程序中的任意位置获得所需的结果。

答案 12 :(得分: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));

答案 13 :(得分: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)
}

答案 14 :(得分:0)

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

String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;
相关问题