すわりんのブログ

androidとかサブカルとかのブログです

Databindingでincludeタグを使う

databindingはincludeタグも上手く扱ってくれるが includeされる側もlayoutタグを仕込まないと bindingが機能しない

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        orientaion="vertical"
        >

        <include layout="@layout/content"
           android:id="@+id/content1"
          />
          
        <include layout="@layout/content"
           android:id="@+id/content2"
          />

    </LinearLayout>
</layout>

content.xml

<?xml version="1.0" encoding="utf-8"?>
//laytouで囲むこと!!
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
    
      <TextView
           android:id="@+id/text"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           />

    </LinearLayout>
</layout>

もしlayoutタグで囲まなくても Layoutは想定通りに構築されるが viewへのプロパティが上手く作られない。

layoutのタグの有無にかかわらず、以下のプロパティが生成されるが

  • binding.content1
  • binding.content2

layoutタグが無い場合、DataBindingClassは同一のViewをセットするからだ。

//同じViewをセットしてしまっている!

そのためonClickListnerなどを設定すると 想定外の動きをしてしまうので注意しよう。

所要時間:5分