モケラ

Tech Sheets

mokelab

データバインディング用のレイアウトXMLを作る

最終更新日:2022-05-08

データバインディングで使用するレイアウトXMLは、通常のレイアウトXMLとちょっとだけ異なります。

ちょっとだけ の部分ですが

  • ルート要素をlayout にする
  • layout の子にビューの親を移動させる

と、これだけです。サンプルを示します。説明のため、ファイル名をmain_fragment.xmlとしておきます。

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/text_label_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginStart="8dp"
            android:textAppearance="?android:textAppearanceLarge"
            android:text="@string/name"/>
        <TextView
            android:id="@+id/text_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginStart="8dp"
            android:layout_below="@+id/text_label_1"/>

        <TextView
            android:id="@+id/text_label_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_name"
            android:layout_marginTop="8dp"
            android:layout_marginStart="8dp"
            android:textAppearance="?android:textAppearanceLarge"
            android:text="@string/age"/>
        <TextView
            android:id="@+id/text_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginStart="8dp"
            android:layout_below="@+id/text_label_2"/>
    </RelativeLayout>
</layout>

一覧に戻る