縦または横一列に要素を並べるリニアレイアウト (LinearLayout)

LinearLayout とは?

リニアレイアウト (LinearLayout) はもっとも単純なレイアウトの一つで、子供の要素を縦または横の一列に並べるレイアウトです。android:orientation 属性に vertical または horizontal を指定することで、それぞれ縦、横に並べることができます。

例えば、次の例では LinearLayout を用いて、子要素(この場合は Button 三つ) を一列に並べています。

Android リニアレイアウト

コードは次のようになります。

<?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"
    >
    <Button
      android:id="@+id/button_1" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Button 1"/>
    <Button
      android:id="@+id/button_2"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" 
      android:text="Button 2"/>
    <Button
      android:id="@+id/button_3" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Button 3"/>
</LinearLayout>

ちなみに、幅や高さを指定する値として fill_parent、wrap_content などとしていますが、 ここはそれぞれ、次のような意味になります。 API レベル8以上では fill_parentとせず match_parentとします。

意味
fill_parent親要素のサイズまでなるべく大きくなるようにする。(ただし、パディング分を引く)
match_parentfill_parentと同じ。 API レベル8以降は fill_parentではなく、match_parentとする。
wrap_contentコンテントを表示できる程度の大きさ

ためしに横に並べてみましょう。

orientationを horizontal として、それぞれのボタンの大きさを、表示可能程度のサイズ (wrap_content) とします。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
      android:id="@+id/button_1" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 1"/>
    <Button
      android:id="@+id/button_2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" 
      android:text="Button 2"/>
    <Button
      android:id="@+id/button_3" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 3"/>
</LinearLayout>

この結果、次のようにボタンが横並びで表示できました。

Android リニアレイアウト

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Android 開発入門