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

Androidで縦向き・横向きごとに異なるレイアウトを指定する方法

この記事では、Androidアプリで縦向き(ポートレート)と横向き(ランドスケープ)のそれぞれに異なるレイアウトを指定する方法を、実際のサンプルコードとともにわかりやすく解説します。

ステップ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:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f2f6f4"
    android:padding="10dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button"
        android:layout_centerInParent="true"
        android:layout_marginTop="16sp"
        android:text="Portrait Mode"
        android:textSize="24sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Show Orientation mode" />
</RelativeLayout>

ステップ3:横向き用のレイアウトを作成する

次に、横向き専用のレイアウトファイルを作成します。リソース(res)フォルダ上で右クリックして新しいレイアウトファイルを作成し、ファイル名を入力したら、「Available qualifiers」から「Orientation」を選択してください。

続いて「≫」ボタンをクリックし、UI modeの一覧から「Landscape」を選びます。

これで res/layout-land/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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginStart="64dp"
        android:layout_toEndOf="@id/button"
        android:text="Landscape Mode"
        android:textSize="24sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginStart="128dp"
        android:text="Show Orientation mode" />
</RelativeLayout>

ステップ4:MainActivityにコードを追加する

src/MainActivity.kt に以下のコードを追加します。ボタンがタップされると、Configurationクラスを使って現在の画面の向きを判定し、その結果をToastで表示します。

import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var textView: TextView
    lateinit var button: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.tvLayout)
        button = findViewById(R.id.button)
        button.setOnClickListener {
            if (button.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                Toast.makeText(this@MainActivity, "We are in portrait mode",
                    Toast.LENGTH_SHORT).show()
            }
            else {
                Toast.makeText(this@MainActivity, "We are in Landscape mode",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}

ステップ5:AndroidManifest.xmlを記述する

最後に、androidManifest.xml を以下のように記述します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.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端末がパソコンに接続されているものとします。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択すると、端末に初期画面が表示されます。

Androidで縦向き・横向きごとに異なるレイアウトを指定する方法

Androidで縦向き・横向きごとに異なるレイアウトを指定する方法

このように、layout-landフォルダに横向き用のレイアウトを配置するだけで、端末の向きに応じてレイアウトが自動的に切り替わります。さらにKotlinコード側でConfigurationによる向き判定を組み合わせれば、画面の向きに合わせた柔軟なUIを実現できます。

  1. Androidでカスタム通知レイアウトとテキストの色を作成する方法を徹底解説

    このチュートリアルでは、Androidアプリにおいて標準的な通知と、RemoteViewsを使ったカスタム通知レイアウトの両方を作成する方法を、サンプルコード付きでわかりやすく解説します。カスタムレイアウトを活用すれば、通知のデザインやテキストの色などを自由にコントロールできるようになります。 全体の流れ 本記事の手順は以下の通りです。 Android Studioで新規プロジェクトを作成する メイン画面のレイアウト(activity_main.xml)を用意する MainActivity.javaに通知の生成処理を実装する 通知・カスタム通知・通知内容表示用のレイアウトXMLを作成する A

  2. PCとAndroidでGoogleセーフサーチをオンにする方法を徹底解説

    インターネットは、まさに世界の情報スーパーハイウェイです。日常生活に役立つ膨大な有益な情報がある一方で、同じくらいたくさんの不快で危険なコンテンツも存在しています。うっかり入力したひとつの検索ワードによって、望ましくないコンテンツがGoogleの検索履歴に残り、オンライン上のプロファイルデータの一部になってしまうこともあるのです。幸いにも、Googleでは検索エンジンの利用時に不適切なコンテンツをフィルタリングする機能が提供されています。PCで検索結果をフィルタリングする方法まず、GmailのメインページにアクセスしてGoogleアカウントにログインします。画面右上にあるプロフィール写真をクリ