LinearLayoutを扱う
LinearLayoutを使うときのポイント
orientation
layout_weight
layout_gravity
/gravity
orientation
orientation
は、子ビューをどの方向に並べるかを設定するプロパティ。
LinearLayout
の最も基本的な機能であり、vertical
(縦方向、上から下へ)とhorizontal
(横方向、左から右へ)の2つの設定がある。
注意点: LinearLayout
自体にはスクロール機能がないため、画面に収まらない場合は ScrollView
や HorizontalScrollView
の中にLinearLayout
を配置する必要がある。
layout_weight
layout_weight
は、LinearLayout
内の子ビューの大きさを比率で決めるプロパティ。
複数のビューを均等に配置したい場合などに非常に便利で、layout_weight
を使う際は、**layout_width
**または layout_height
を **0dp
**に設定する必要がある。
例えば、3つのTextViewを横に均等な幅(1:1:1)で並べる場合は以下。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="左" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="中" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="右" />
</LinearLayout>
ヘッダー、フッター、そして残りの全領域をコンテンツに割り当てるようなレイアウトにも利用可能。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ヘッダ領域" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="コンテンツ領域" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="フッタ領域" />
</LinearLayout>
layout_gravity
と gravity
適用対象が異なる点に注意が必要なプロパティ。
layout_gravity
:LinearLayout
内の子ビューの位置を、親のLinearLayout内で指定する。gravity
:LinearLayout
自身内のコンテンツ全体の位置を指定する。
例: orientation="vertical"
のLinearLayout
内で、TextView
にlayout_gravity="end"
を設定すると、
そのTextView
は右寄せで配置される。これは親のLinearLayout
のorientation
設定(縦並び)とは別の軸での配置になる。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="左" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="中" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="右" />
</LinearLayout>
gravity
を適用した場合
もし親のLinearLayout
にgravity="center"
を設定すると、以下のようにすべての内容が中央に寄る。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
</LinearLayout>
このときlayout_gravity
が設定されていた「左」は右寄せのままで、
何も設定されていなかった「右」は中央寄せになる。これは、layout_gravity
が親のgravity
の設定を上書きするため。
参考
最終更新: 2025.9.9