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

【Kotlin】実行時にAndroidビューのサイズを取得する方法を徹底解説

Kotlinで実行時にAndroidビューのサイズを取得する方法

このチュートリアルでは、Kotlinを使用してAndroidアプリの実行時にビュー(View)のサイズ(幅・高さ)を取得する方法を、サンプルコード付きでステップごとに解説します。

ポイント:ViewTreeObserver.OnGlobalLayoutListenerとは?

Androidでは、onCreate() の時点ではまだレイアウトの測定(measure)と配置(layout)が完了していないため、findViewById() で取得した直後に widthheight を参照しても「0」が返されます。そこで、グローバルレイアウトの完了時に通知される ViewTreeObserver.OnGlobalLayoutListener を利用することで、正確なビューのサイズを取得できます。

ステップ1:新規プロジェクトの作成

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

ステップ2:レイアウトファイルの編集

res/layout/activity_main.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="8dp"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:layout_gravity="center"
        android:src="@drawable/image" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:layout_centerInParent="true"
        android:layout_marginTop="20sp"
        android:textColor="@android:color/background_dark"
        android:textSize="16sp"
        android:textStyle="bold" />
</RelativeLayout>

ステップ3:画像リソースの配置

任意の画像ファイル(.png / .jpg / .jpeg)を res/drawable フォルダにコピー&ペーストします。

ステップ4:MainActivity.ktの実装

src/MainActivity.kt に以下のコードを追加します。

import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    private lateinit var imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        imageView = findViewById(R.id.imageView)
        imageView.viewTreeObserver.addOnGlobalLayoutListener(GetViewSize())
    }
    internal inner class GetViewSize : OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val view = findViewById<View>(R.id.imageView)
            val x = view.width.toString()
            val y = view.height.toString()
            (findViewById<View>(R.id.textView) as TextView).text = String.format("Width %s, Height: %s", x, y)
        }
    }
}

このコードでは、ImageView の ViewTreeObserver に OnGlobalLayoutListener を登録し、レイアウト描画が完了したタイミングでビューの幅(width)と高さ(height)を取得して TextView に表示しています。

ステップ5:AndroidManifest.xmlの設定

androidManifest.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q11">
    <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」アイコンをクリックします。表示された候補から接続中のモバイルデバイスを選択すると、端末の画面にImageViewの幅と高さが表示された結果画面が確認できます。

【Kotlin】実行時にAndroidビューのサイズを取得する方法を徹底解説

  1. Androidでビューのサイズ(幅・高さ)を取得する方法をわかりやすく解説

    Androidアプリ開発では、XMLレイアウトにあらかじめビューを定義するのではなく、Javaコードから動的にビューを生成したいケースが多くあります。動的に生成したビューは、画面に描画されるまで実際のサイズが確定しないため、幅や高さを取得してレイアウトを調整したり、他の処理に活用したりする必要があります。この記事では、Androidでビューのサイズ(幅・高さ)を取得するシンプルな方法を、サンプルコード付きで解説します。 ビューのサイズを取得する基本の方法 ビューの高さと幅を取得するには、それぞれ次のメソッドを使用します。 ビューの高さを取得する int height = view.get

  2. 【Android】実行時にViewのサイズ(幅・高さ)を取得する方法をわかりやすく解説

    この記事では、Androidアプリの実行時にViewのサイズ(幅・高さ)を動的に取得する方法を、サンプルコード付きで段階的に解説します。レイアウトが描画される前は getWidth() や getHeight() を呼んでも正しい値が取得できないため、ViewTreeObserver の OnGlobalLayoutListener を利用して、レイアウト完了後にサイズを取得するのがポイントです。手順1:新規プロジェクトを作成するAndroid Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。手順2:レイアウトファイ