web-dev-qa-db-ja.com

androidでプログラムで画面サイズを取得する方法

Androidは、画面サイズをNormal Large XLargeなどとして定義しています。

適切なフォルダー内の静的リソースを自動的に選択します。 Javaコードで現在のデバイスに関するこのデータが必要です。DisplayMetricsは現在のデバイス密度に関する情報のみを提供します。画面サイズに関しては何も利用できません。

GrepコードでScreenSize列挙型を見つけました here しかし、これは4.0 SDKでは利用できないようです。この情報を取得する方法はありますか?

69
user1454356

このコードをコピーして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();
113
Alex Lockwood
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 + "}";
}
48
David

画面サイズの決定:

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

12
Anshu P

このコードを使用して、ピクセル単位で表示サイズを取得できます。

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

これを試すことができます、それは動作しています

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
Takermania
DisplayMetrics displayMetrics = new DisplayMetrics();

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

int width = displayMetrics.widthPixels;

int height = displayMetrics.heightPixels;
2
omor

私はそれが非常に単純なコードだと思います!

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

これが誰かに役立つかもしれないし、使いやすいと思うかもしれません。再修正または改善が必要な場合は、遠慮なくお知らせください! :-)

乾杯!!!

2
Randika Vishman

いくつかのアプリでこれが必要であり、次のコードが問題の解決策でした。 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
Tequilaman

サイモン-

画面サイズが異なると、ピクセル密度も異なります。お使いの携帯電話の4インチディスプレイには、多かれ少なかれピクセルがあり、26インチテレビと言えます。 Imが正しく理解している場合、彼は現在の画面がどのサイズグループであるか、小さい、普通、大きい、特大を検出したいと考えています。私が考えることができる唯一のことは、ピクセル密度を検出し、それを使用して画面の実際のサイズを決定することです。

1
Kevin Brey

非アクティビティ、つまりフラグメント、アダプタ、モデルクラス、またはその他のJavaを拡張しないクラスActivity単にgetResources())が機能しない場合。フラグメントでgetActivity()を使用するか、対応するクラスに渡すcontextを使用できます。

mContext.getResources()

一般的な作業のためのメソッド/メソッドを持つUtilsと言うクラスを作成することをお勧めします。この利点は、このメソッドを呼び出すアプリ内の任意の場所にある1行のコードで目的の結果を得ることができることです。

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
Alex Kon

私は何かが欠けているに違いない。 DisplayMetrics.widthPixels、DisplayMetrics.heightPixels?

http://developer.Android.com/reference/Android/util/DisplayMetrics.html#heightPixels

[編集]

ああ、私は何かが欠けています。脳!アレックスの+1。

0
Simon