1
0

More than 1 year has passed since last update.

Androidの双方向データバインディングで`cannot be inverted, so it cannot be used in a two-way binding`を解決する

Posted at

はじめに

最近、Jetpack Composeばっかりやっていたのですが、久しぶりにxmlをやって思い出そうということで復習がてら勉強していたのですが、そこで双方向データバインディングをやろうとした時に、cannot be inverted, so it cannot be used in a two-way bindingこのエラーで少しだけ時間がかかったので、今回はこれを解決してみます。

原因

原因はシンプルでした。
僕は、今まで単方向しか書いたことがなかったのでViewModelで以下のような書き方をしていました。

private val _username = MutableLiveData<String>()
val username: LiveData<String> = _username

private val _password = MutableLiveData<String>()
val password: LiveData<String> = _password

しかしこれで双方向をやろうとすると、、、、、

The expression 'viewmodelUsername.getValue()' cannot be inverted, so it cannot be used in a two-way binding

Details: There is no inverse for method getValue, you must add an @InverseMethod annotation to the method to indicate which method should be used when using it in two-way binding expressions

こんな感じのエラーが出てきました。ネットで調べてもなかなか解決策が出てこなかったのですが、以下のように書くことで、このエラーを解決できました。

val username = MutableLiveData<String>()

val password = MutableLiveData<String>()

DataBindingに関して

そもそも双方向データバインディングをどのようにやるのかに関しては、他にもたくさん記事があるので、今回は省略します。以下僕が勉強した時に参考にしたサイトです。

https://zenn.dev/kmd_htsh0226/articles/8579dff07c6f4ed84576
https://qiita.com/naoi/items/29c16746fa0fe9e8355d

1
0
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
0