1
1

More than 3 years have passed since last update.

【Android】DataBindingのvariableはcamelCaseで書く

Last updated at Posted at 2020-06-28
<variable name="hoge_text" type="String">

より、

<variable name="hogeText" type="String">

のが困らないと思うっすという話。プチハマったので。

具体例

「被<include>ファイルでsnake_caseのvariableを使おうとしたらアクセスできなかった」

書いてみるxml

child.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="value_text"
            type="String" />
    </data>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{value_text}"/>
</layout>
parent.xml
<親要素省略>
    <include
        layout="@layout/child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:value_text="@{someVariable}"/>
</親要素省略>

生成されるコード

ChildBindingImpl.java
    public void setValueText(@Nullable java.lang.String ValueText) {
        this.mValueText = ValueText;
        synchronized(this) {
            mDirtyFlags |= 0x2L;
        }
        notifyPropertyChanged(BR.value_text);
        super.requestRebind();
    }
ParentBindingImpl.java
    @Nullable
    private final app.package.name.databinding.ChildBinding mboundView;
// ~~~ 略 ~~~
            this.mboundView.setValue_text(someVariableGetValue); // <- お前ー!!

エラー内容

エラー: シンボルを見つけられません
            this.mboundView3.setValue_text(someVariableGetValue);
                            ^
  シンボル:   メソッド setValue_text(String)

というわけで、app:snake_case属性により生成される関数名が、
<variable name="snake_case">により生成される関数名と異なるためビルドに失敗します。

「じゃあapp:camelCase&<variable name="snake_case">ならどうよ」という気もしますが、
その場合はxmlファイル側で名前の解決が出来ず、BindingImplの生成前にエラーになるようです。書く側としてもxml内でその切り替えはしんどいっす。(自分の場合)

対処

冒頭に書いた通りです。

child.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="valueText"
            type="String" />
    </data>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{valueText}"/>
</layout>
parent.xml
<親要素省略>
    <include
        layout="@layout/child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:valueText="@{someVariable}"/>
</親要素省略>

定義からcamelCaseにしましょう。

おまけ

あんまり明言はされてないと思うんですが、
公式のサンプルでも2単語の変数名をさがしました。camelCaseでした。(userList

    <data>
        <import type="com.example.User"/>
        <import type="java.util.List"/>
        <variable name="user" type="User"/>
        <variable name="userList" type="List&lt;User>"/>
    </data>

このあたり(じゃあresourceのidもcamelCaseにしとく? とか)はGoogle提供のコードでも一貫されていない感があるので、昔から小さく話題になることみたいですね。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1