LoginSignup
35
32

More than 5 years have passed since last update.

Androidで画面サイズを取得する方法

Posted at

Androidで画面サイズを取得するのに、従来はDisplayクラスのgetWidth()/getHeight()メソッドを使っていたが、API level 13以降では非推奨(Deprecated)になっています。

代わりに、getSize(Point point)メソッドが追加されていて、こちらを使うようにとのことです。ただし、このgetSize()メソッドはAPI level 13より前では存在しません。そのため、API level 13をまたぐコードを書く場合は、注意が必要です。

下記StacOverflowの回答がとても参考になったので、コード部分をメモとして引用します。
stacoverflow : Android get Screen Size deprecated?

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
overrideGetSize(display, size);

void overrideGetSize(Display display, Point outSize) {
    try {
      // test for new method to trigger exception
      Class pointClass = Class.forName("android.graphics.Point");
      Method newGetSize = Display.class.getMethod("getSize", new Class[]{ pointClass });

      // no exception, so new method is available, just use it
      newGetSize.invoke(display, outSize);
    } catch(NoSuchMethodException ex) {
      // new method is not available, use the old ones
      outSize.x = display.getWidth();
      outSize.y = display.getHeight();
    }
}
35
32
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
32