画面の向きによってレイアウトを変更する
|端末の液晶画面は基本的に長方形です。アプリによっては端末の向きを変えることで、縦長のポートレートモード(portrait)と横長のランドスケープモード(landscape)でレイアウトが変わるものや、向きを変えてもレイアウトが固定されているものがあります。
例えば、エミュレータの電話アプリでは下記の画像のように、ポートレートとランドスケープでレイアウトが変わります。
エミュレータで端末(画面)の向きを変える場合は「CTRL + F11」を押してください。
それでは、実際に横向き用、縦向き用のレイアウトを用意したい場合にどのようにしたらよいかなどを続きで説明します。
layout-landフォルダ
res以下にlayout-landフォルダを準備します。
ですがその前に、まず準備しないとどうなるか試してみましょう。以下のようなレイアウトファイルを準備します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <pre><?xml version= "1.0" encoding= "utf-8" ?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" android:layout_width= "fill_parent" android:layout_height= "fill_parent" > <ImageView android:id= "@+id/ImageView01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/eclair" > </ImageView> <Button android:text= "@string/button" android:id= "@+id/Button01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" > </Button> <AnalogClock android:id= "@+id/AnalogClock01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" > </AnalogClock> </LinearLayout> |
端末が縦の時と横の時の画像です。LinearLayoutを利用してorientationをverticalに設定しているので横向きの時に縦方向が窮屈ですね。
それではランドスケープ用のレイアウトを用意しましょう。
繰り返しになりますが、まずres以下にlayout-landフォルダを準備します。
そして同じファイル名でレイアウトファイルを準備します。 今回は同じくLinearLayoutを利用してorientationをhorizontalにしてみます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?xml version= "1.0" encoding= "utf-8" ?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "horizontal" android:layout_width= "fill_parent" android:layout_height= "fill_parent" > <ImageView android:id= "@+id/ImageView01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/eclair" > </ImageView> <Button android:text= "@string/button" android:id= "@+id/Button01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" > </Button> <AnalogClock android:id= "@+id/AnalogClock01" android:layout_width= "wrap_content" android:layout_height= "wrap_content" > </AnalogClock> </LinearLayout> |
動作させたら下記のように横向き(LandScape)の時にはlayout-landフォルダ以下のレイアウトファイルを読み込んでくれるようになります。
画面の向きを固定したいとき
ゲームアプリなどでは画面の向きを固定したい時があると思います。その場合は、AndroidManifest.xmlにてActivityにandroid:screenOrientationを設定します。
- portrait:縦向きに固定
- landscape:横向きに固定
試しに縦向きに固定してみます。
1 2 3 | <activity android:name= ".ScreenOrientationSampleActivity" android:label= "@string/app_name" android:screenOrientation= "portrait" > |
このように端末を横にしてもポートレートのままでランドスケープになりません。