LoginSignup
2

More than 5 years have passed since last update.

DataBindingとObservableField使用時にハマったこと

Posted at

結論

public な ObservableField が入ったViewModelクラスを作る際には、get"ObservableField名"のメソッドをクラス内に作ってはいけない

前提

  • Android Studio 2.3.1
  • com.android.tools.build:gradle:2.2.3

問題の起きるコード

ViewModel.java
public class ViewModel {
    public ObservableField<String> text = new ObservableField<>();
    public ObservableLong id = new ObservableLong(0);

    public String getText(){
        return this.text.get();
    }

    public void setText(String text){
        this.text.set(text);
    }

    public Long getId() {
        return this.id.get();
    }

    public void setId(long id) {
        this.id.set(id);
    }
}
layout.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">

    <data>

        <variable
            name="viewModel"
            type="com.example.ViewModel" />
    </data>

    <FlameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.example.CustomView
            android:id="@+id/custom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:Text="@{viewModel.text}"
            app:Id="@{viewModel.id}" />
    </FlameLayout>
</layout>
BindingAdapter.java
public class BindingAdapters {
    @BindingAdapter({"Text"})
    public static void setCustomViewText(CustomView customView, String text) {
        customView.setText(text);
    }

    @BindingAdapter({"Id"})
    public static void setCustomViewId(CustomView customView, long id) {
        customView.setId(id);
    }
}

起きること

  • 上記のViewModelインスタンスのsetIdメソッドを呼んでもsetCustomViewIdメソッドが呼ばれない

解決法

  • ViewModel.javaからgetTextとgetIdメソッドを削除する

原因

  • ObservableField hogeの値をgetするメソッドの名前をgetHogeにするとなぜかActivityHugaBindingクラスにonChangeHogeViewModelメソッドが作られないなど、自動コード生成の一部に不正が発生し、ObservableFieldの値が更新されてもそれを検知できない

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
2