[Android] LinaerLayout:ビューを単一方向に並べる

LinearLayout(リニアレイアウト)とは、全ての子ビューを垂直方向もしくは水平方向の一方向に並べるレイアウトです。ここでは、LinearLayoutの基本的な使い方を説明します。
広 告
目次
前提条件
動作確認端末
- Google Nexus 5 – 5.0.0 – API21(エミュレータ)
1. LinearLayout概要
リニアレイアウトを使用するためにはLinearLayoutクラスか<LinearLayout>
タグを使います。子ビューは、レイアウトXMLファイルの上から記述した順番に並んで表示されます。並び方向が「垂直」に指定されている場合は上から下へ、並び方向が「水平」に指定されている場合は左から右に並びます。
2. レイアウトの並び方向を決める
LinearLayoutの子ビューの並び方向はandroid:orientation属性で指定します。垂直方向の場合は、
android:orientation="vertical"
水平方向の場合は、
android:orientation="horizontal"
と指定します。
3. layout_weightで占有率を指定する
LinearLayout
は、android:layout_weight属性をサポートしています。android:layout_weight
は、android:orientation
で指定された方向への占有率を定義することができます。
占有率について、例を使って説明します。android:orientation="vertical"
が指定されたLinearLayout
の子ビューに3つのビューがあります。その内1つのビューにはandroid:layout_height
に”50dp"
を指定し、残りの2つのビューには"0dp"
が指定します。この2つのビューにandroid:layout_weight
の値を、それぞれ"1"
と"2"
と指定します。すると2つのビューの高さは、画面の高さから50dp
(3つ目のビューの”50dp"
)を差し引いた高さを1 : 2 に割り振った値になります(端末の画面の高さによって値は変動します)。それぞれ"1"
と"1"
と指定すると、画面の高さから"50dp"
を差し引いた高さを1 : 1に割り振った値になります。
これが占有率の考え方です。
Note : android:layout_weightを使うことでLinearLayoutの子ビューを全て均等な長さに並べることができます。
android:orientation="vertical"
の場合は、全ての子ビューに以下の属性を指定することで可能です。
android:layout_height="0dp" android:layout_weight="1"
android:orientation="horizontal"
の場合は、全ての子ビューの以下の属性を指定することで可能です。
android:layout_width="0dp" android:layout_weight="1"
4. LinearLayoutの使い方
以下に、LinearLayoutを使ったサンプルコードを示します。
/app/src/main/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical" > <!-- @string/destinationの参照は「送信先」--> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/destination" /> <!-- @string/subjectの参照は「件名」--> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/subject" /> <!-- @string/bodyの参照先は「本文」--> <EditText android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:hint="@string/body" /> <!-- @string/sendの参照先は「送信」--> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/send" /> </LinearLayout>
実行すると以下のような画面になります。
