Webエンジニアのメモ帳

技術的な話を中心に書いています。

【Android開発】ConstraintLayoutで横幅の比率を指定して要素を配置する

AndroidアプリをConstraintLayoutを使って開発している場合に、横幅の比率を指定して要素を配置する方法を説明します。

結論を最初に書くと、xmlファイルで以下を指定すればOKです。

  1. android:layout_widthを0dpで指定する
  2. app:layout_constraintHorizontal_weightで横幅(比率)を指定する

実装例

以下は、私が勉強も兼ねて開発している家計簿アプリの一部です。

f:id:iberia9lavapies:20220218112225p:plain

金額を入力するフォームと「円」の文字列を5:1の比率で表示しているのですが、このときのxmlファイルは以下のようになっています。

<EditText
  android:id="@+id/edit_money"
  android:inputType="number"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  app:layout_constraintHorizontal_weight="5"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toLeftOf="@id/yen"
  app:theme="@style/EditTextStyle"/>
<TextView
  android:id="@+id/yen"
  android:paddingStart="15dp"
  android:textSize="15dp"
  android:textStyle="bold"
  android:text="円"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  app:layout_constraintHorizontal_weight="1"
  app:layout_constraintLeft_toRightOf="@id/edit_money"
  app:layout_constraintRight_toRightOf="parent"/>