Androidプログラマへの道 〜 Moonlight 明日香 〜 - 画面の向きを設定する
画面の向きは, 縦/横方向に固定あるいはセンサによる自動切り換えに設定できる.
設定する方法はいくつかある.

画面の向き

    • 画面の向きを設定する属性
属性値説明API Level
unspecifiedSCREEN_ORIENTATION_UNSPECIFIED端末の設定により動作が異なる(デフォルト)1
landscapeSCREEN_ORIENTATION_LANDSCAPE横固定(ノーマル)1
portraitSCREEN_ORIENTATION_PORTRAIT縦固定(ノーマル)1
userSCREEN_ORIENTATION_USER現在のレイアウトに従う1
behindSCREEN_ORIENTATION_BEHIND親のアクティビティに従う1
sensorSCREEN_ORIENTATION_SENSORセンサ状態に従う. ユーザの端末の持ち方に依存1
nosensorSCREEN_ORIENTATION_NOSENSORセンダ状態に従わない以外はunspecifiedと同じ1
sensorLandscapeSCREEN_ORIENTATION_SENSOR_LANDSCAPE横方向(ノーマル/リバース). センサ状態に従う9
sensorPortraitEEN_ORIENTATION_SENSOR_PORTRAIT縦方向(ノーマル/リバース). センサ状態に従う9
reverseLandscapeSCREEN_ORIENTATION_REVERSE_LANDSCAPE横固定(リバース)9
reversePortraitSCREEN_ORIENTATION_REVERSE_PORTRAIT縦固定(リバース)9
fullSensorSCREEN_ORIENTATION_FULL_SENSORセンサ状態に従う9

Activity#setRequestedOrientationメソッドで設定

  • Orientation.java
    • Activity#setRequestedOrientationメソッドで, 画面の向きを設定する.
package com.moonlight_aska.android.orientation;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;

public class Orientation extends Activity implements View.OnClickListener {
  private Button btn01 = null;
  private Button btn02 = null;
  private Button btn03 = null;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btn01 = (Button)findViewById(R.id.btn01_id);
    btn02 = (Button)findViewById(R.id.btn02_id);
    btn03 = (Button)findViewById(R.id.btn03_id);
    btn01.setOnClickListener(this);
    btn02.setOnClickListener(this);
    btn03.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == btn01) {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else if(v == btn02) {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    else if(v == btn03) {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }
  }
}

AndroidManifest.xmlで設定

  • AndroidManifest.xml
    • android:screenOrientationに画面の向きを設定する.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.moonlight_aska.android.orientation"
   android:versionCode="1"
   android:versionName="1.0">
  <uses-sdk android:minSdkVersion="4" />

  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".Orientation"
       android:label="@string/app_name" android:screenOrientation="landscape">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>

動作例:
1) 縦方向


2) 横方向