LoginSignup
37
36

More than 5 years have passed since last update.

画面の向きを動的に設定する

Posted at

端末の向きと画面の向き設定によらず、画面の向きを指定したい場合がある。

静的に指定する場合

下記のようにAndroidManifest.xmlで指定する。

  • 縦固定
AndroidManifest.xml
<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait">
  • 横固定
AndroidManifest.xml
<activity
    android:name=".MainActivity"
    android:screenOrientation="landscape">
  • 自動
AndroidManifest.xml
<activity
    android:name=".MainActivity"
    android:screenOrientation="unspecified"> <!-- 未指定でもOK! というか、普通は未指定 -->

動的に指定する場合

下記のように Activity#setRequestedOrientation を呼び出す。
呼び出した結果、実際に画面の向きが変わった場合はActivityが再生成される(android:onConfigChangesでorientation等を指定していなければ)。

  • 縦固定
MainActivity.java
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  • 横固定
MainActivity.java
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  • 自動
MainActivity.java
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
37
36
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
37
36