Androidレイアウトにおけるlayout_weightの使用方法とは

Androidにおけるlayout_weightは、親コンテナの中の残りのスペースを割り当てるためのプロパティです。LinearLayoutなどと合わせて使用し、ビュー同士を相対的な割合で配置する場合によく用いられます。

具体的には次のように使います。

  1. LinearLayoutなどを使って縦横のレイアウト方向を設定し、子ビューの合計ウェイトを表す値にweightSumプロパティを設定します。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="3">
  1. 子ビューに、親ビューに対して占める比率を表す数字をレイアウトウェイトとして設定します。
<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Text 1" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:text="Text 2" />

上の例では、子ビュー1の重みが1、子ビュー2の重みが2となっています。そのため、子ビュー2は親コンテナの2倍のスペースを占有します。

  1. 子ビューにlayout_widthやlayout_heightを0dpに設定すると、重みによって幅または高さを自動的に割り当てられます。
<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Text 1" />

上で示した例の ChildView1 の幅は、重みによって自動的に調整されて、親コンテナの残りの空間を埋めます。

LinearLayoutのレイアウトで子ビューの相対的な比率を設定するために使用され、余白空間を均一に割り当てたり、重みによってビューのサイズを決定するなど、柔軟なレイアウトを実現できます。

广告
広告は10秒後に閉じます。
bannerAds