Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidデバイスの画面の高さ・幅を取得する方法【サンプルコード付き】

この記事では、Androidアプリで端末の画面の高さ(Height)幅(Width)を取得する方法を、実際に動作するサンプルコードとともにステップごとに解説します。あわせて、画面サイズ(インチ数)を計算して表示する方法も紹介します。

仕組みのポイント:DisplayMetricsクラス

Androidでは、DisplayMetricsクラスを使うことで、画面のピクセル数や密度(dpi)といったディスプレイ情報を簡単に取得できます。本記事のサンプルでは、このクラスを利用して画面の高さ・幅・インチ数を求めていきます。

手順1:Android Studioで新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

手順2:activity_main.xml にレイアウトを定義する

res/layout/activity_main.xml に以下のコードを追加します。画面の高さ・幅・インチ数をそれぞれ表示するためのTextViewを3つ配置しています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/getScreenHeight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/getScreenWidth"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/getScreenInches"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold" />
</LinearLayout>

手順3:MainActivity.java に処理を記述する

src/MainActivity.java に以下のコードを記述します。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView height, width, inches;
    DisplayMetrics displayMetrics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        height = findViewById(R.id.getScreenHeight);
        width = findViewById(R.id.getScreenWidth);
        inches = findViewById(R.id.getScreenInches);

        displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int screenHeight = displayMetrics.heightPixels;
        int screenWidth = displayMetrics.widthPixels;

        // 三平方の定理を使って画面の対角線の長さ(インチ数)を計算
        double y = Math.pow(screenHeight / displayMetrics.xdpi, 2);
        double x = Math.pow(screenWidth / displayMetrics.xdpi, 2);
        double screenInches = Math.sqrt(x + y);
        screenInches = (double) Math.round(screenInches * 10) / 10;

        height.setText("Screen Height: " + screenHeight);
        width.setText("Screen Width: " + screenWidth);
        inches.setText("Screen Inches: " + screenInches);
    }
}

コードのポイントは以下の通りです。

  • getWindowManager().getDefaultDisplay().getMetrics(displayMetrics) で、現在のディスプレイ情報をDisplayMetricsオブジェクトに格納します。
  • heightPixelswidthPixels から、画面の高さと幅をピクセル単位で取得できます。
  • xdpi(1インチあたりのドット数)で割り、三平方の定理を適用することで、画面の対角線の長さ=インチ数を求めています。

補足: getDefaultDisplay() はAPIレベル30(Android 11)以降で非推奨となっています。Android 11以降をターゲットとする新規プロジェクトでは、WindowManager#getCurrentWindowMetrics() で取得できる WindowMetrics の利用が推奨されます。

手順4:AndroidManifest.xml を確認する

androidManifest.xml は以下の内容になります。画面サイズの取得には特別なパーミッションは不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

アプリを実行して結果を確認しよう

それでは、作成したアプリケーションを実行してみましょう。ここでは、実機のAndroidスマートフォンをPCに接続しているものとして説明します。

Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。デバイス選択のダイアログで自分のモバイル端末を選択すると、端末の画面に以下のように結果が表示されます。

Androidデバイスの画面の高さ・幅を取得する方法【サンプルコード付き】

  1. Androidの画面をテレビに映す方法6選!ChromecastからHDMI接続まで徹底解説

    Androidデバイスで見ている動画や画像を、もっと大きな画面で楽しみたいと思ったことはありませんか?Androidの画面をテレビやPCにキャスト(ミラーリング)すれば、大画面での視聴が実現します。一部の方法ではAndroidデバイスがMiracastに対応している必要がありますが、選択肢はそれだけではありません。この記事では、初心者でも簡単にできる6つの方法を詳しく解説します。YouTubeやNetflixなどの動画を、快適な大画面で楽しんでみましょう。1. Chromecastを使うGoogleが推奨しているのは、Chromecastを使ったキャスト方法です。お使いのAndroidデバイス

  2. Androidの画面に音量ボタンを表示する方法|物理キーが壊れても安心な対処法

    Androidスマートフォンには、端末側面に音量を調節するための物理ボタンが搭載されています。音楽やポッドキャストを聴いているとき、動画を見ているときなど、これらのボタンを使えば簡単に音量をコントロールできます。しかし場合によっては、この物理キーが音量を調節できる唯一の手段になっていることもあります。そのため、ボタンが故障したり破損したりすると、非常に不便に感じてしまうでしょう。 とはいえ、音量キーが壊れたり押し込まれて動かなくなったりしても、諦める必要はありません。画面から直接音量を操作できる便利な回避策がいくつか存在します。 Androidには、物理ボタンを使わずに音量を調節できるアプリが