Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@Gazyu

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

More than 3 years have passed since last update.

結論

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の値が更新されてもそれを検知できない
2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?