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

【Android】ボタン操作で画面の向き(縦向き・横向き)をプログラム的に切り替える方法

この記事では、Androidアプリでボタンをタップするだけで画面の向き(縦向き・横向き)をプログラム的に切り替える方法を解説します。

画面の向きを切り替える仕組み

画面の向きの変更には、ActivityクラスのsetRequestedOrientation()メソッドを使用します。引数にActivityInfo.SCREEN_ORIENTATION_PORTRAIT(縦向き)またはActivityInfo.SCREEN_ORIENTATION_LANDSCAPE(横向き)を指定することで、任意のタイミングで画面の向きを固定できます。

ステップ1:新規プロジェクトを作成する

Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要事項を入力してプロジェクトを作成しましょう。

ステップ2:レイアウトファイル(activity_main.xml)

res/layout/activity_main.xml に以下のコードを追加します。「縦向きに変更」「横向きに変更」の2つのボタンを配置しています。

<?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"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonSetPortrait"
        android:text="縦向きに変更"
        android:textColor="@color/colorPrimaryDark"
        android:textStyle="bold"
        android:layout_marginTop="62dp"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonSetLandscape"
        android:text="横向きに変更"
        android:textColor="@color/colorPrimaryDark"
        android:textStyle="bold"
        android:layout_marginTop="24dp"
        android:layout_below="@+id/buttonSetPortrait"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

ステップ3:MainActivity.java の実装

src/MainActivity.java に以下のコードを追加します。各ボタンにクリックリスナーを設定し、タップされたときに setRequestedOrientation() を呼び出して画面の向きを切り替えています。

package app.com.sample;

import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button buttonSetPortrait = (Button) findViewById(R.id.buttonSetPortrait);
        Button buttonSetLandscape = (Button) findViewById(R.id.buttonSetLandscape);

        buttonSetPortrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 縦向きに固定する
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });

        buttonSetLandscape.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 横向きに固定する
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        });
    }
}

※最新のAndroid Studioでは、supportライブラリの代わりに androidx.appcompat.app.AppCompatActivity をインポートしてください。

ステップ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スマートフォンをパソコンに接続しているものとします。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デバイスの選択画面で接続したスマートフォンを指定すると、実機に以下のような初期画面が表示されます。

【Android】ボタン操作で画面の向き(縦向き・横向き)をプログラム的に切り替える方法

【Android】ボタン操作で画面の向き(縦向き・横向き)をプログラム的に切り替える方法

まとめ

setRequestedOrientation() メソッドを使えば、ボタン操作ひとつで画面の向きを自由に制御できます。動画プレイヤーやゲームなど、横向き表示が適した場面でぜひ活用してみてください。

  1. AndroidでプログラムからScrollViewを無効化する方法

    このチュートリアルでは、AndroidアプリでScrollViewをプログラム的に無効化する方法を解説します。setOnTouchListener()を使ってタッチイベントを横取りすることで、ユーザーによるスクロール操作を防ぐことができます。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。 ステップ2:レイアウトファイルの編集(res/layout/activity_main.xml) 以下のコードを res/lay

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

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