LinearLayoutで子要素の幅を比率指定する方法をメモ。
layout_widthを0dpで指定する。wrap_contentや固定値にした場合は幅が意図しない挙動になる。縦方向で使う場合はorientationをverticalに指定し、layout_heightの値を0dpにする。ConstraintLayoutの中では動作せず。LinearLayoutの機能になっている。他にLinearLayoutを継承しているChipGroupやRadioGroupでも使用できる
下記コードは1:2:2の幅比率になっている。
<LinearLayout
android:id="@+id/linearLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent">
<TextView
android:id="@+id/textView01"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/colorBlue"
android:text="左側" />
<TextView
android:id="@+id/textView02"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@color/colorGreen"
android:text="真ん中" />
<TextView
android:id="@+id/textView03"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@color/colorRed"
android:text="右側" />
</LinearLayout>
layout_weightを実装しようとした時に、まだ何となくで仕様を把握していなかったので改めてまとめた。
参考