LoginSignup
2
2

More than 5 years have passed since last update.

Android Data Binding Libraryでandroid:onClickにBind

Posted at

最近じわじわと来ている、AndroidでMVVMライクな体験ができるライブラリ Data Binding Libraryですが、.NETのWPFっぽくonClickにOnClickListenerをBindしようとするとエラーがでるという現象に遭遇しました。

2つ解決策を見つけたので記しておきます。解決策①が簡単です。

したいこと

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="@{viewModel.hogeCommand}"/>

ViewModel側

public class ViewModel {

    public View.OnClickListener getHogeCommand() {

        return hogeCommand;
    }
}

解決策①

android:onClickの代わりにandroid:onClickListenerを使う

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClickListener="@{viewModel.hogeCommand}"/>

解決策②

Renamed Setters を使う
ViewModel側

@BindingMethods({
    @BindingMethod(type = Button.class,
                attribute = "android:onClick",
                method = "setOnClickListener")
})
public class ViewModel {

    @BindingMethod(type = Button.class,
                attribute = "android:onClick",
                method = "setOnClickListener")
    public View.OnClickListener getHogeCommand() {

        return hogeCommand;
    }
}
2
2
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
2
2