0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Android端末の画面の向きを取得する

0
Posted at

Androidアプリで現在の画面が縦向きか横向きかを判定する方法をメモします。

現在の画面の向きを取得する

画面の向きは Configuration クラスから取得できます。

import android.content.res.Configuration

val orientation = resources.configuration.orientation

when (orientation) {
    Configuration.ORIENTATION_PORTRAIT -> {
        // 縦向き
    }
    Configuration.ORIENTATION_LANDSCAPE -> {
        // 横向き
    }
    Configuration.ORIENTATION_UNDEFINED -> {
        // 不明
    }
}

画面の向き変更を検知する

onConfigurationChanged() を利用を利用することで端末を回転した際にイベントを受け取り検知することができます。

検知したいActivityからManifestに以下設定を追加します。

<activity
    android:name=".MainActivity"
    android:configChanges="orientation|screenSize" />

対象のActivity から向きの変化を受け取ります。

import android.content.res.Configuration

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)

    when (newConfig.orientation) {
        Configuration.ORIENTATION_PORTRAIT -> {
            // 縦になった
        }

        Configuration.ORIENTATION_LANDSCAPE -> {
            // 横になった
        }
    }
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?