具有正确的xml绑定的livedata变量的2种方式的数据绑定错误

时间:2019-10-03 08:48:54

标签: android kotlin viewmodel android-livedata

在activity_login.xml中,我的登录活动有一个loginViewModel

class LoginViewModel : ViewModel(){
    private val _phoneNumber = MutableLiveData<String>()
    val phoneNumber : LiveData<String>
        get() = _phoneNumber
}

在我的loginViewModel中,我将livedata定义为

The expression \u0027loginViewModelPhoneNumber.getValue()\u0027 cannot be inverted, so it cannot be used in a two-way binding\n\nDetails: 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

现在,在构建时出现以下错误

sidekiq_redis_url: redis://localhost:6379
sidekiq_redis_pwd: redispwd

我正在阅读的所有文章都建议采用这种方法。 有人可以告诉我我在做什么错吗?

4 个答案:

答案 0 :(得分:1)

更改
private val _phoneNumber = MutableLiveData<String>()

public val _phoneNumber = MutableLiveData<String>()

答案 1 :(得分:0)

您正在绑定phoneNumber,这是一个LiveData,没有任何写入值的接口。

考虑删除phoneNumber,并使用基于Kotlin的方法,仅使用公共财产

答案 2 :(得分:0)

不幸的是,对于双向数据绑定,您需要使用MutableLiveData。

您应在_phoneNumber上删除私人。

然后更改xml以使用它android:text="@={loginViewModel._phoneNumber}"

答案 3 :(得分:0)

代码有几个问题。

  • 您尝试使用在双向绑定中不可变的val phoneNumber,因此只有吸气剂,因此绑定类只能从字段读取值,以从UI接收数据-绑定类希望使用setter,但不存在setter,因此phoneNumber不会更改。

  • 对于绑定phoneNumber的属性,您尝试使用不可更改的LiveData-应该使用MutableLiveData,以防需要更改。 / p>

  • 如果您想听phoneNumber的变化,则需要像

  • 一样添加LiveData Observer
phoneNumber.observe{
  val value = it
}

希望有帮助。