Android内のlayout_weight属性の設定方法
Android のレイアウトファイルでは、layout_weight 属性を使用してウィジェットの重みを設定できます。
layout_weight属性は、ウイジェットがレイアウト上で取るスペースの割合を指定するために使用される浮動小数点数です。デフォルトでは、全てのウイジェットのlayout_weight値は0になっています。
レイアウトの重み属性を使用するには、LinearLayoutをコンテナとして使う必要があります。なぜなら、LinearLayoutだけが重み付けをサポートするレイアウトコンテナだからです。
LinearLayoutのlayout_weight属性を設定する例を次に示します。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="TextView 1" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:text="TextView 2" />
</LinearLayout>
上述の例では、LinearLayoutのorientation属性はverticalに設定されているため、子コントロールは縦に並んでいます。TextViewコントロールのlayout_width属性はmatch_parentに設定されており、幅は親と同じです。一方で、layout_height属性は0dpに設定されており、ウェイト値はlayout_weight属性によって設定されています。
重み値の設定により、最初のTextViewの重みは1、2番目のTextViewの重みは2となる。つまり2番目のTextViewの高さは最初のTextViewの2倍になる。
layout_weightプロパティを設定することで、柔軟にレイアウト内のコントロールの占めるスペースの割合を調整することができます。